← Runtimes
Runtimes

How a type checker works

Rules, demands and unknowns: what the compiler does with your types.

A type checker applies language rules and follows constraints; acceptance alone does not establish intent.

Outcome

Predict a checker’s verdict from its rules, trace where a literal gets its type, and follow unification to the demand where a conflict is reported.

Terminology (4)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Typing rule
What operand types an operation accepts and what type its result has.
Synthesis
Computing a node’s type from its children’s types, bottom up.
Type variable
A placeholder for a type the checker does not know yet.
Unification
Solving equality constraints between types. This lab only has flat int/bool types and unknown aliases; it resolves and joins those aliases before binding a group to a known type.

Types as rules and constraints

A type checker analyzes a program’s syntax using types associated with names and expressions. A typing rule states which premises an operation requires and what type follows from them. Computing an expression’s type from its parts is called synthesis; checking can also compare it with a type demanded by its context.

When some types are unknown, inference collects constraints from their uses. A type variable stands for an unknown, and unification reconciles demands that must agree. Different languages permit different operations and conversions, so their checkers can reach different verdicts on similar-looking source. The small checker later in this lesson has its own explicitly bounded rules.

01Rules

What does the checker allow for text + number?

The order service is adding type checks before operations staff save validation rules. Quantities should be compared as numbers and flags combined as booleans. First inspect what the host languages accept for a cart quantity and a warehouse total, then choose the rules for the editor’s small language. An input left unknown must acquire a consistent type from its uses.

The rule editor needs a policy for add: numeric quantities in, numeric quantity out. A host language may permit a different operation for the same characters. A checker tests the operand types against its language’s rules; accepting this operation establishes that type rule, not the cart behavior its author intended.

In each program, a cart line’s quantity arrives from the cart API as the text "3", and the add-one button adds 1 to it.

quantity is a string. TypeScript’s + has a rule for string and number.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// A cart line's quantity arrives from the cart API as text; the add-one button adds 1.

const quantity: string = "3";
const total = quantity + 1;

console.log(`total = [${total}]`);
What happens?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc main.ts --noEmit --strict && node main.ts

The quoted outcomes are historical 1 November 2026 runs with versions and flags recorded in the author evidence. Some native examples are meant to be rejected. Rust’s byte-sum prediction uses the recorded overflow-check-enabled build; release/debug labels alone do not fix those flags. The lab later models its own flat type rules, not these compilers’ inference algorithms.

02Context

Where does a literal get its type?

Before the rule editor treats a warehouse total as an int, trace the host expression that supplies it. A numeric literal can get a type from the operation or storage context; inference can also use a related later annotation. That type determines which arithmetic rules the host applies.

The warehouse scanner feed sends each bin’s unit count as one byte. Each program stores two bins’ counts, 250 and 10, as bytes and totals them for the stock page.

A Uint8Array stores bytes, but reading an element gives a number.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// The scanner feed sends each bin's unit count as one byte; the stock page totals two bins.

const units = new Uint8Array(2);
units[0] = 250;
units[1] = 10;

console.log(`sum = ${units[0]! + units[1]!}`);
What does it print?

03Unknowns

Where is a conflict reported?

Operations staff may leave an input such as limit unknown while composing a rule. The lab’s flat int/bool checker gives it a placeholder and joins placeholders that must agree. It resolves aliases before processing each demand; a demand for a known type binds the group, and an incompatible later demand fails. A join between two unknowns can leave both still unknown.

This authored checker visits child expressions left to right before making their parent’s demands, and processes commands in order. It reports its first disagreeing demand. Real compilers can collect or solve constraints differently and choose other diagnostic locations; the source mistake can still be far from the reported conflict.

The order service’s rule checker infers types in source order. In a saved validation rule, line 1 declares limit with no type, line 2 uses limit + 1, and line 9 uses limit as a condition. Where is the conflict reported?

04Practice

Finish the type checker

The lab supplies the order-rule language’s parser and traversal. Define result types, check the known-type demands, then infer flat int/bool unknowns and aliases. This incremental checker retains demands made before an error; it does not roll back a whole failed check or model a transactional save. Each level supplies the parts that already work. Only complete, exact-arity prefix expressions and unique declarations are supported; general syntax diagnostics are outside this checker.

The type checker

Give each operation its type, report broken rules, then infer unknown types.

  1. easy · R-TYPES-V4-1 Give each operation its type
  2. medium · R-TYPES-V4-2 Report broken rules
  3. hard · R-TYPES-V4-3 Infer unknown types
In the frontend A numeric assertion does not convert a cart value Optional

The cart endpoint returns JSON containing the string "3". This helper is under review: its TypeScript return type says number, and the add-one operation passes static checking. What value does the returned promise actually contain?

The same TypeScript helper can serve a Next or Svelte cart. Its type assertion supplies a premise to the checker; the received value still needs to meet that premise at runtime.

lib/cart/next-quantity.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
export async function nextQuantity(response: Response): Promise<number> {
  const quantity = (await response.json()) as number;
  return quantity + 1;
}

The assertion is erased. A TypeScript success does not validate JSON or parse numeric text; this helper’s runtime result can violate its declared return type.

Sources: TypeScript: assertions have no runtime checks.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.