Skip to content
Tutorials Center
My learning

Topics

Lesson 84 of 96 ยท Projects

Project: Typed Calculator

Build a calculator in TypeScript - tokenize and parse expressions into a typed tree, evaluate with a Result type, then drive a keypad with a typed reducer and DOM-shaped bindings.

A calculator looks trivial, yet it hides two classic programs: an expression evaluator (turn the text 2 + 3 * (4 - 1) into a number) and a keypad state machine (what happens when you press 7, +, 3, = on a pocket calculator). In this project you build both, in three stages, and every stage is a complete program you can run.

The ideas you will practice: discriminated unions for tokens and actions, recursive types for the expression tree, a Result type for errors, an exhaustive reducer and a DOM-shaped interface so the logic stays testable.

Stage 1: the expression evaluator

The pipeline has three steps. A tokenizer turns characters into tokens. A parser turns tokens into a tree that respects operator precedence. An evaluator walks the tree.

The tree is a recursive discriminated union, so every node is either a number or an operation with two children:

TypeScript Stage 1: tokenizer, parser and evaluator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Study how the types help. evaluate has an inner switch on expr.op, and TypeScript knows the function returns on every path, because each case returns and all operators are covered (add a sixth operator to the union and the compiler complains that the function can end without returning). A Result<T> forces the caller to check ok before touching value, so a division by zero can never leak out as Infinity. Rounding to ten decimals hides floating point noise like 0.30000000000000004.

The grammar is encoded in the call order: additive calls multiplicative, which calls unary, which calls power, which calls primary. Lower precedence sits higher in the chain, which is why 2 + 3 * 4 multiplies first.

Stage 2: the keypad state machine

A pocket calculator has no parser. It reacts to key presses one at a time, and the display depends on what was pressed before. That is a perfect fit for a reducer: a pure function (state, action) => state.

TypeScript Stage 2: a typed keypad reducer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Two habits worth copying. The reducer's switch covers every member of Key, and the function's return type guarantees every path returns a state. And because reduce is pure, testing it is just press('12+7='): no buttons, no DOM, no mocks. The fresh flag is the small piece of memory that makes the calculator feel right: after pressing an operator, the next digit starts a new number instead of appending to the old one.

Stage 3: connecting the keypad to the page

The last step connects the reducer to buttons and a screen. As in Project: DOM Widgets, we describe only the slice of the DOM we need as small interfaces, so the same code works with real elements in a browser and with simple stand-ins here.

TypeScript Stage 3: a calculator bound to DOM-shaped elements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

In a browser the wiring is a few lines, because real HTMLElement and HTMLButtonElement already satisfy ScreenLike and ButtonLike:

TypeScript
const screen = document.querySelector('#screen');
const buttons = [...document.querySelectorAll<HTMLButtonElement>('button[data-key]')];

if (screen) {
  mountCalculator(screen, buttons);
}
HTML
<div id="screen">0</div>
<button data-key="7">7</button>
<button data-key="+">+</button>
<button data-key="=">=</button>

Notice keyFromButton returns Key | null. A button with an unknown data-key (the 'oops' button above) is skipped instead of crashing, and the null check makes TypeScript prove that the reducer only ever receives valid keys.

Ideas to extend it

  • Connect stage 1 to stage 2: add an "expression mode" with a text input that calls calculate.
  • Add memory keys (M+, MR) as new union members; the compiler will point at every switch that needs updating.
  • Add a history list of results, stored as readonly entries.
  • Write tests with Vitest that feed key sequences into the reducer.
  • Support keyboard input by mapping KeyboardEvent.key to a Key.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the parser call additive, then multiplicative, then unary in that order?

    + and - are parsed at the top, and each operand is itself a *// expression, so multiplication happens first.
  2. 2. What does the Result<T> type force the caller to do?

    value exists only on the ok: true branch, so TypeScript requires narrowing first.
  3. 3. What is the benefit of writing the keypad logic as a pure reducer?

    A pure function from (state, key) to state needs no browser, so tests are simple.
  4. 4. Why does mountCalculator take ScreenLike and ButtonLike instead of HTMLElement?

    Structural typing lets any object with those members be passed.
  5. 5. What does the fresh flag in the state record?

    After an operator or equals, a new number starts, so the next digit overwrites the screen.

Summary

  • A calculator is two programs: an expression evaluator (tokenizer, recursive descent parser, evaluator) and a keypad state machine.
  • Tokens, expression nodes and keys are discriminated unions; exhaustive switch statements keep every case handled.
  • Operator precedence is encoded by which parse function calls which.
  • Result<T> makes errors such as division by zero explicit instead of leaking Infinity or exceptions.
  • A pure reducer keeps keypad logic testable; DOM-shaped interfaces keep it separate from the page.

Next: Project: Password Generator and Unicode Finder