9. Type Checking
Catching errors before runtime
You can add two numbers. You can concatenate two strings. But what happens when you try to add a number to a boolean? In a dynamically typed language, you find out at runtime — sometimes in production. A type checker finds these mistakes before the code ever runs.
Type checking is surprisingly similar to interpretation. Where an interpreter walks the AST and computes values, a type checker walks the AST and computes types. Same structure, different domain.
Why types?
Consider this function:
fn area(width, height) {
return width * height;
}
area(10, "twenty"); // Runtime error: can't multiply number by string
Without types, this crashes at runtime. With type annotations and a checker:
fn area(width: number, height: number): number {
return width * height;
}
area(10, "twenty"); // Compile error: expected number, got string
The error moves from runtime to compile time — from "the user found a bug" to "the programmer found a bug." That's the core value proposition of static types.
Static vs. dynamic typing
In a statically typed language (TypeScript, Rust, Java, Haskell), every expression has a type known at compile time. The type checker rejects programs that contain mismatches.
In a dynamically typed language (Python, JavaScript, Ruby), values carry their types at runtime and operations check types on the fly. You get more flexibility but less safety.
Most modern languages blend both: TypeScript adds static types on top of JavaScript, Python has optional type hints, Dart has sound null safety. The trend is toward more static checking, not less.
A simple type checker
Let's build a type checker for our toy language. The structure mirrors the evaluator — a recursive function that visits each AST node — but instead of computing a value, it returns a type.
First, we need types to work with:
const Type = {
NUMBER: 'number',
STRING: 'string',
BOOLEAN: 'boolean',
VOID: 'void',
ERROR: 'error', // propagates through expressions
};
function typeToString(t) {
if (typeof t === 'string') return t;
if (t.kind === 'function') {
const params = t.params.map(typeToString).join(', ');
return `(${params}) => ${typeToString(t.returnType)}`;
}
return 'unknown';
}
Type-checking expressions
The heart of the checker is a function that takes an AST node and a type environment, and returns the type of that expression:
function checkExpr(node, env) {
switch (node.type) {
case 'NumberLiteral':
return Type.NUMBER;
case 'StringLiteral':
return Type.STRING;
case 'BoolLiteral':
return Type.BOOLEAN;
case 'Identifier':
return env.get(node.name); // look up declared type
case 'BinaryExpr':
return checkBinary(node, env);
case 'CallExpr':
return checkCall(node, env);
}
}
Literals are trivial — a number literal has type number, a string literal has
type string. Identifiers look up their type in the type environment (which
maps variable names to types, not values). The interesting cases are binary
expressions and function calls.
Checking binary expressions
Each operator has rules about what types it accepts and what type it produces:
function checkBinary(node, env) {
const left = checkExpr(node.left, env);
const right = checkExpr(node.right, env);
switch (node.op) {
case '+':
// number + number = number
if (left === Type.NUMBER && right === Type.NUMBER)
return Type.NUMBER;
// string + string = string (concatenation)
if (left === Type.STRING && right === Type.STRING)
return Type.STRING;
// anything else is an error
return typeError(
node, `Cannot apply + to ${left} and ${right}`
);
case '-': case '*': case '/':
if (left === Type.NUMBER && right === Type.NUMBER)
return Type.NUMBER;
return typeError(
node, `Cannot apply ${node.op} to ${left} and ${right}`
);
case '<': case '>': case '==': case '!=':
if (left === right) return Type.BOOLEAN;
return typeError(
node, `Cannot compare ${left} with ${right}`
);
}
}
The + operator is special: it works on both numbers and strings, but not a
mix. This is exactly the kind of rule that a type checker encodes. In a
dynamically typed language, "hello" + 3 might silently produce "hello3" or
throw an error depending on the language — a type checker makes the rule
explicit and consistent.
Type environments
Just as the interpreter has environments that map names to values, the type checker has environments that map names to types. The structure is identical:
class TypeEnv {
constructor(parent = null) {
this.types = new Map();
this.parent = parent;
}
define(name, type) {
this.types.set(name, type);
}
get(name) {
if (this.types.has(name)) return this.types.get(name);
if (this.parent) return this.parent.get(name);
throw new Error(`Undefined variable: ${name}`);
}
}
When the checker encounters a variable declaration with a type annotation, it records the type:
case 'LetStmt': {
const initType = checkExpr(node.init, env);
if (node.annotation) {
// let x: number = 5;
if (initType !== node.annotation) {
typeError(node,
`Type ${initType} is not assignable to ${node.annotation}`
);
}
env.define(node.name, node.annotation);
} else {
// let x = 5; — infer the type from the initializer
env.define(node.name, initType);
}
break;
}
Notice the two paths: if there's an explicit annotation, we check that the
initializer matches. If there isn't, we infer the type from the initializer.
This simple form of type inference
is what TypeScript does with let x = 5 — the type is inferred as number.
Checking functions
Functions have a signature — the types of their parameters and return value:
case 'FnDecl': {
const paramTypes = node.params.map(p => p.annotation);
const funcType = {
kind: 'function',
params: paramTypes,
returnType: node.returnAnnotation || Type.VOID,
};
// Define the function's type before checking the body (for recursion)
env.define(node.name, funcType);
// Check the body in a new environment with parameters defined
const bodyEnv = new TypeEnv(env);
for (let i = 0; i < node.params.length; i++) {
bodyEnv.define(node.params[i].name, paramTypes[i]);
}
const returnType = checkBlock(node.body, bodyEnv);
if (node.returnAnnotation && returnType !== node.returnAnnotation) {
typeError(node,
`Function returns ${returnType} but declared ${node.returnAnnotation}`
);
}
break;
}
And checking a function call verifies that the argument types match the parameter types:
function checkCall(node, env) {
const calleeType = checkExpr(node.callee, env);
if (calleeType.kind !== 'function') {
return typeError(node, `Cannot call non-function type ${calleeType}`);
}
if (node.args.length !== calleeType.params.length) {
return typeError(node,
`Expected ${calleeType.params.length} arguments, got ${node.args.length}`
);
}
for (let i = 0; i < node.args.length; i++) {
const argType = checkExpr(node.args[i], env);
if (argType !== calleeType.params[i]) {
typeError(node,
`Argument ${i + 1}: expected ${calleeType.params[i]}, got ${argType}`
);
}
}
return calleeType.returnType;
}
Beyond simple types: a taste of inference
Our type checker so far requires explicit annotations on function parameters. But what about more powerful inference — figuring out types with no annotations at all?
The gold standard is Hindley-Milner type inference, used by Haskell, OCaml, and ML. The idea has two phases:
1. Constraint generation. Walk the AST and generate equations between types.
For let x = a + b, you'd generate: "the type of a must equal the type of b,
and the type of x must equal the type of a."
2. Unification. Solve the equations. If you know a is a number, the
equations tell you b and x must be numbers too. The algorithm finds the most
general type that satisfies all constraints.
// Simplified constraint generation for a + b
function generateConstraints(node) {
if (node.type === 'BinaryExpr' && node.op === '+') {
const tLeft = freshTypeVar(); // create unknown type T1
const tRight = freshTypeVar(); // create unknown type T2
const tResult = freshTypeVar(); // create unknown type T3
return [
...generateConstraints(node.left), // constrain T1
...generateConstraints(node.right), // constrain T2
{ lhs: tLeft, rhs: tRight }, // T1 == T2
{ lhs: tResult, rhs: tLeft }, // T3 == T1
];
}
if (node.type === 'NumberLiteral') {
return [{ lhs: node.typeVar, rhs: Type.NUMBER }];
}
}
Full Hindley-Milner is too involved for this article (it's a deep topic on its own), but the core insight is beautiful: types can be inferred systematically by treating type checking as a constraint-satisfaction problem.
Union types
Sometimes a variable can be more than one type:
fn parseInput(s: string): number | string {
let n = toNumber(s);
if (n != null) return n;
return s;
}
A union type
like number | string means the value could be either. The type checker must
ensure you handle both possibilities before doing type-specific operations:
let result = parseInput("42");
// result is number | string here
if (typeof result == "number") {
// result is narrowed to number here
print result + 1;
} else {
// result is narrowed to string here
print result + "!";
}
This narrowing — tracking how control flow refines a union type — is called type narrowing, and it's one of TypeScript's most beloved features.
The big picture
A type checker is a second interpreter that runs at compile time over types instead of values:
| Interpreter | Type checker |
|---|---|
| Environment: name to value | Type env: name to type |
evaluate(expr) returns a value |
checkExpr(expr) returns a type |
2 + 3 returns 5 |
number + number returns number |
| Runtime error on mismatch | Compile error on mismatch |
This parallel structure means you can add type checking to any language with an AST. The tree-walking type checker runs first, reports errors, and if everything passes, the regular interpreter or compiler runs as before. Types are erased at runtime — they've already done their job.
Try It Yourself — Type Checker
Write code with type annotations. The checker will analyze your program and report any type errors it finds. Try introducing mismatches (like adding a number to a string) and see what the checker catches.