Languages and runtimesDive 01 of 08
TypeScript: inside the compiler
Follow one generic function through tokens, symbols, control flow and type inference. Compare the compiler’s JavaScript and declaration output, then inspect the types it computes.
- Levels
- 8
- Reading
- 28 min
- Depth
- Idea to Runtime
- Published
One source file, two outputs
Take the guard off result.value and TypeScript reports an error. Put the guard back and your editor can tell you the receiver has a different type inside the branch. Open the generated JavaScript and you will find the guard, the property access and no trace of either type. How does the compiler know enough to complain about code that the JavaScript engine will happily execute?
Our running example reads a count. A successful result carries a number and a failure carries a message. Generic code cares only that the fallback and the success payload have the same type. The literal ok field lets the caller decide which shape it has, and gives the compiler evidence it can use to narrow the union.
export type Result<T> =
| { ok: true; value: T }
| { ok: false; error: string };
export function unwrap<T>(result: Result<T>, fallback: T): T {
if (result.ok) return result.value;
return fallback;
}
export function readCount(result: Result<number>) {
return unwrap(result, 0);
}export function unwrap(result, fallback) {
if (result.ok)
return result.value;
return fallback;
}
export function readCount(result) {
return unwrap(result, 0);
}
//# sourceMappingURL=result.js.mapexport type Result<T> = {
ok: true;
value: T;
} | {
ok: false;
error: string;
};
export declare function unwrap<T>(result: Result<T>, fallback: T): T;
export declare function readCount(result: Result<number>): number;The JavaScript preserves the operations a runtime needs. The declaration file preserves the types another TypeScript project needs, including the inferred number return type of readCount. In the same build, a source map records how positions in the JavaScript correspond to positions in the original file. Save the source as result.ts in a scratch directory and compile it to see all three outputs.
npx --yes --package typescript@7.0.2 tsc result.ts \
--strict --target es2022 --module esnext \
--declaration --sourceMap --outDir outFrom text to declarations
The scanner reads the source text and recognizes tokens. The parser decides what those tokens mean grammatically. It can recognize result.ok from an identifier, a dot and a property name, then make that property access the condition of an if statement. The token stream answers what the characters spell. The abstract syntax tree, or AST, answers what role each part plays.
Here is the portion of the AST for the guard, with source positions and other metadata omitted. Both occurrences of result are separate identifier nodes. Each points to its own span of source text. Source spans let an editor highlight the right occurrence or a diagnostic underline the exact property access.
IfStatement
├─ expression: PropertyAccessExpression
│ ├─ expression: Identifier ("result")
│ └─ name: Identifier ("ok")
└─ thenStatement: ReturnStatement
└─ expression: PropertyAccessExpression
├─ expression: Identifier ("result")
└─ name: Identifier ("value")Binding makes declarations discoverable
The binder walks the tree, records declarations as symbols, and stores those symbols in the appropriate scopes. Both identifier occurrences in the tree above can resolve to unwrap’s parameter symbol. The parameter of readCount happens to have the same spelling and lives in a different scope. A symbol can represent several compatible declarations. For example, two mergeable interface declarations can contribute members to the same symbol.
Symbols also carry information about the meanings a declaration contributes. A type alias contributes a type meaning. A function contributes a value meaning. A class contributes both, so class Job lets you write let job: Job in a type position and new Job() in an expression. References are interpreted according to their position and lexical scope.
These are distinct pieces of data. A node describes syntax at a position. A symbol describes a named entity and its declarations. A type describes the possibilities the checker can assign to an expression or declaration. The binder also records control flow, which lets the checker compute different types for references to one symbol.
A different type at each use
At the start of unwrap, the checker knows that result could be either member of the union. Both members have an ok property, so reading it is valid and gives a boolean. Only the success member can have ok equal to true. Reaching the return in that branch is evidence that result.value exists and has type T.
The property ok is the union’s discriminant. The declared type stays Result<T>. A query at a particular reference can use the flow graph to compute a narrower type. The native checker starts with that reference and follows antecedent flow nodes, applying facts from preceding conditions and assignments. At a join, it accounts for the incoming paths that can reach the reference.
export type Result<T> =
| { ok: true; value: T }
| { ok: false; error: string };
export function unwrap<T>(result: Result<T>, fallback: T): T {
if (result.ok) return result.value;
return fallback;
}- Receiver at the read
{ ok: true; value: T; }- Property type
T
True (result.ok) ─ Startexport type Result<T> =
| { ok: true; value: T }
| { ok: false; error: string };
export function unwrap<T>(result: Result<T>, fallback: T): T {
return result.value;
}- Receiver at the read
Result<T>- Property type
- Access rejected
StartTS2339: Property 'value' does not exist on type 'Result<T>'.
Property 'value' does not exist on type '{ ok: false; error: string; }'.export type Result<T> =
| { ok: true; value: T }
| { ok: false; error: string };
export function unwrap<T>(result: Result<T>, fallback: T): T {
if (!result.ok) return fallback;
return result.value;
}- Receiver at the read
{ ok: true; value: T; }- Property type
T
False (!result.ok) ─ Startexport type Result<T> =
| { ok: true; value: T }
| { ok: false; error: string };
export function unwrap<T>(result: Result<T>, fallback: T): T {
if (!result.ok) {
fallback;
}
return result.value;
}- Receiver at the read
Result<T>- Property type
- Access rejected
Branch ┬ True (!result.ok) ─┬ Start
╰ False (!result.ok) ╯TS2339: Property 'value' does not exist on type 'Result<T>'.
Property 'value' does not exist on type '{ ok: false; error: string; }'.export type Result<T> =
| { ok: true; value: T }
| { ok: false; error: string };
export function unwrap<T>(result: Result<T>, fallback: T): T {
if (result.ok) {
result = { ok: false, error: "stale" };
return result.value;
}
return fallback;
}- Receiver at the read
{ ok: false; error: string; }- Property type
- Access rejected
Assignment (result) ─ True (result.ok) ─ StartTS2339: Property 'value' does not exist on type '{ ok: false; error: string; }'.Walk backward from the property read
With Guard selected, the reference points to True (result.ok). That node links back to Start, where the parameter can be either member. The checker uses the true condition to filter the union before it attempts the property lookup. Choose No guard and the read points straight to Start. There is no intervening evidence, so TS2339 reports the member that lacks value.
In Early return, the graph for the later read contains only False (!result.ok). This is the false outcome of the negated condition, so result.ok was true. The failing path returned and has no edge to the read. In Branches rejoin, remove that return and both outcomes reach the read. The Branch node has two inputs, and combining them restores the original union.
In Reassignment, the assignment node is closer to the use than the original test. The assignment is legal against the declared Result<T>, but the read now sees the failure member. The diagnostic changes accordingly. It names the failure object directly because that is the only remaining possibility.
Nothing from the true branch can reach the last line because that branch returns. If the last line were return result.error, reading error there would be valid, although returning a string as an unconstrained T would still fail. Property access and return-type compatibility are separate checks.
The native TypeScript 7.0.2 CLI confirms the missing-guard result. The excerpt below is from a native run of the same edit.
error TS2339: Property 'value' does not exist on type 'Result<T>'.
Property 'value' does not exist on type '{ ok: false; error: string; }'.Assignments can change the observed type too. After assigning a number to a variable declared as string | number, its next read can have type number. A later assignment of a string is still checked against the declared union. When a discriminant test eliminates every possibility, the remaining type is never. That is what makes an exhaustiveness check work. Adding a union member causes a previously exhaustive branch to produce a value that cannot be assigned to never.
How the checker compares types
Many diagnostics boil down to a directional question. Can a value of source type S be used where the target type T is expected? For ordinary object shapes, the checker looks for the target’s required properties and compares their types. The source can have additional properties. The direction matters because swapping source and target can change which properties are required.
function readId(value: { id: string }) {
return value.id;
}
const item = { id: "count", extra: true };
readId(item); // accepted
readId({ id: "count", extra: true }); // TS2353: excess propertyBoth calls supply objects with an id. The inline literal receives an extra check for properties absent from the target, which is how TypeScript catches a likely misspelling in an options object. That check applies to fresh literals in the relevant contexts. It does not turn { id: string } into an exact object type.
Functions make the direction especially visible. A handler that can accept any message with an id can also handle messages with a count. Assign a count-only handler to a slot meant to accept arbitrary messages, and the caller could legally pass { id: "x" }. Now message.count is missing. Under strictFunctionTypes, the assignment below fails for a function type. Method syntax has a compatibility exception that allows bivariant parameter checking.
type Message = { id: string };
type CountMessage = Message & { count: number };
let handle: (message: Message) => void;
const handleCount = (message: CountMessage) =>
console.log(message.count.toFixed());
handle = handleCount; // TS2322 under strictFunctionTypesThe native checker implements multiple type relations. Assignability handles ordinary assignments and arguments. Identity asks a stricter equality question, while comparability serves contexts such as equality tests. The implementation can answer simple cases directly and descend into properties, signatures and constituent types for harder cases. It caches relation results, which matters when different expressions lead back to the same pair of recursive object types.
Inferring and computing types
In unwrap(result, 0), the first argument contributes number by matching the success member of Result<number> against the success member of Result<T>. The second argument contributes the literal type 0. The compiler has two candidates for one parameter, so it has to decide what type to use before it checks the instantiated signature.
| Argument | Source type | Parameter type | Candidates for T |
|---|---|---|---|
result | Result<number> | Result<T> | number |
0 | 0 | T | number, 0 |
(result: Result<number>, fallback: number): numberThe probe records the inference context immediately after each argument flows through inferTypes. These are covariant candidates, collected from values flowing into the call. The checker combines the candidates and chooses number in this case. It already admits the literal 0. Candidate combination can depend on inference priority, literal widening and constraints on the parameter. The resolved signature is the result of substituting the choice into the parameters and return type. The capture uses an in-memory probe of the installed compiler and the public checker API for the final signature.
Information also moves from an expected type into an expression. An array of numbers gives map an expected callback type, so the compiler can give its unannotated parameter n the type number. The callback body then supplies evidence for the result type. Moving an expression out of its original context can change the inferred result because the new location supplies different expectations.
const readCountCallback = (result: Result<number>) =>
unwrap(result, 0);
const labels = [1, 2].map(n => n.toFixed()); // string[]
const loose = { ok: true, value: 42 };
// { ok: boolean; value: number }
const checked = { ok: true, value: 42 } satisfies Result<number>;
// { ok: true; value: number }The object bound to loose can still have its properties reassigned, so its ok property widens to boolean. The target in checked supplies a context where the literal discriminant matters. The satisfies operator checks compatibility while preserving the resulting expression type. In this example, that type retains the success shape and ok: true.
Conditional types can inspect an argument
Payload recovers the success payload from the result union. The conditional has a bare type parameter on the left of extends, so the checker distributes it over the union. The success member yields number. The failure member yields never, which contributes nothing to the resulting union. Wrap the checked parameter in a one-element tuple and the conditional tests the whole union at once. The failure member now prevents the match.
type Payload<R> = R extends { ok: true; value: infer V } ? V : never;
type WholePayload<R> =
[R] extends [{ ok: true; value: infer V }] ? V : never;
type A = Payload<Result<number>>; // number
type B = WholePayload<Result<number>>; // never
type OptionalFields<T> = { [K in keyof T]?: T[K] };
type Patch = OptionalFields<{ count: number; label: string }>;
// { count?: number; label?: string }The mapped type at the end walks keyof T, reads each property type with T[K] and adds an optional modifier. Both examples compute types during checking. Their cost depends on the work exposed by the actual inputs. A conditional over a union can instantiate once per member, and nesting two such operations can multiply the number of pairs the checker must consider.
What survives at runtime
The emitter transforms syntax and prints the output. Type aliases, assertions, type arguments and annotations can disappear from JavaScript. Syntax used at runtime follows different rules. A regular enum can generate an object, and a parameter property can generate a property assignment. The target can also change how JavaScript features are emitted. Selecting a library gives the checker declarations for APIs such as Promise and document. The host still has to provide those APIs.
Imagine the count arrives as JSON and contains "42" as a string. Asserting that the result is Result<number> lets the incorrect value through to readCount. The emitted function reads the property exactly as it exists at runtime. A validator can take the parsed value as unknown and check the success and failure shapes before the call.
function isCountResult(input: unknown): input is Result<number> {
if (typeof input !== "object" || input === null || !("ok" in input)) {
return false;
}
if (input.ok === true) {
return "value" in input && typeof input.value === "number";
}
return input.ok === false &&
"error" in input && typeof input.error === "string";
}
const input: unknown = JSON.parse('{"ok":true,"value":"42"}');
if (isCountResult(input)) {
console.log(readCount(input));
} else {
console.log("Invalid count result");
}This reports Invalid count result with the input shown. Replacing "42" in the JSON with 42 makes validation pass and prints 42. The type predicate communicates that guarantee to the checker. The predicate’s body is where the guarantee actually comes from. A body that always returned true could advertise the same signature and admit an invalid result.
Checking and producing JavaScript are distinct operations. tsc --noEmit checks a project without writing JavaScript. noEmitOnError makes compiler diagnostics block output. A bundler or a runtime with built-in type stripping can remove erasable syntax as part of a separate pipeline. A successful run through that pipeline establishes that it could produce or execute JavaScript.
Modules, editors and incremental builds
A program includes the dependencies you check against
The compiler starts with root files from the project configuration, follows imports and references and loads declaration files for the configured environment. An imported dependency can enter the program even when it falls outside an include glob. A dependency’s declarations can describe an implementation supplied by a separate JavaScript file. They can also affect checking in every file that consumes its types.
For a concrete example, add the file below beside result.ts in a project that emits Node ESM. The specifier ./result.js is valid in the generated JavaScript. During checking, TypeScript’s extension substitution can resolve it to result.ts. The explicit type import is erased, and the import of readCount survives.
import type { Result } from "./result.js";
import { readCount } from "./result.js";
const result: Result<number> = { ok: true, value: 42 };
console.log(readCount(result));Packages add another layer. A package can expose different files to importers through its exports map, including a declaration under a types condition. TypeScript’s resolution mode should model the host that loads the modules. If a paths alias only exists in the TypeScript configuration, the emitted specifier still contains that alias and the host can fail to resolve it.
Editors and builds ask different questions
A hover might ask for the type of one reference. Go to Definition resolves a symbol and locates its declaration. Rename must find related references across the project. An editor service can answer requests from in-memory snapshots and reuse work as those snapshots change. A CLI build has a different goal. It can ask for project-wide diagnostics and outputs.
Make an edit that crosses a project boundary
Incremental builds store compiler state in .tsbuildinfo. Project references give build mode a dependency graph and establish a declaration boundary between projects. In this experiment a library exports readCount, and a consumer calls toFixed on the result. Build once in a scratch directory, then change the returned value from 42 to 43. After that, change the return type to string and return "43".
Set up the two projects
mkdir library consumer
cat > tsconfig.json <<'JSON'
{"files":[],"references":[{"path":"./library"},{"path":"./consumer"}]}
JSON
cat > library/tsconfig.json <<'JSON'
{"compilerOptions":{"composite":true,"outDir":"dist","rootDir":"."},"files":["count.ts"]}
JSON
cat > consumer/tsconfig.json <<'JSON'
{"compilerOptions":{"composite":true,"outDir":"dist","rootDir":"."},"files":["app.ts"],"references":[{"path":"../library"}]}
JSON
cat > library/count.ts <<'TS'
export function readCount(): number { return 42; }
TS
cat > consumer/app.ts <<'TS'
import { readCount } from "../library/count.js";
export const label = readCount().toFixed();
TS
npx --yes --package typescript@7.0.2 tsc -b --verboseprintf '%s\n' 'export function readCount(): number { return 43; }' > library/count.ts
npx --yes --package typescript@7.0.2 tsc -b --verboseBuilding project 'library/tsconfig.json'...
Project 'consumer/tsconfig.json' is up to date with .d.ts files from its dependencies
Updating output timestamps of project 'consumer/tsconfig.json'...printf '%s\n' 'export function readCount(): string { return "43"; }' > library/count.ts
npx --yes --package typescript@7.0.2 tsc -b --verbose --pretty falseBuilding project 'library/tsconfig.json'...
Project 'consumer/tsconfig.json' is out of date because output 'consumer/dist/tsconfig.tsbuildinfo' is older than input 'library/dist/count.d.ts'
Building project 'consumer/tsconfig.json'...
consumer/app.ts(2,34): error TS2551: Property 'toFixed' does not exist on type 'string'. Did you mean 'fixed'?Both edits rebuild the library. The first leaves its declaration as readCount(): number. The builder can update the consumer’s output timestamps and reuse its previous result. The second changes the declaration consumed downstream, so the consumer rebuilds and TS2551 points at toFixed. The edits are equally small in source. Their effect on the declaration is what changes the work across projects.
TypeScript 7 also parallelizes parsing, type checking and emit. Checker workers can duplicate some work, so worker count can trade memory for elapsed time. Incremental reuse saves a different kind of work by avoiding an unnecessary check in the first place.
| Question | Compiler command |
|---|---|
| Why is this file part of the project? | tsc --explainFiles |
| Why did this import pick that declaration? | tsc --traceResolution |
| How much time goes into checking versus other work? | tsc --extendedDiagnostics |
| Which files or type operations account for the time? | tsc --generateTrace trace |
Inspect the compiler’s answer
The Compiler API lets you pull apart the answers your editor usually shows as one tooltip. The lab prints the top-level syntax kinds, follows each property-access receiver back to its symbol and asks for the receiver and property types at that location. At the call site it also retrieves the resolved signature after inference.
Use the original result.ts from the first level in a scratch directory. Run npm install --no-save typescript@6.0.3, save the following as inspect.cjs and run node inspect.cjs. The version pin selects the JavaScript Compiler API used in the example.
const ts = require("typescript");
const program = ts.createProgram(["result.ts"], { strict: true, types: [] });
const source = program.getSourceFile("result.ts");
const checker = program.getTypeChecker();
console.log(source.statements.map(node => ts.SyntaxKind[node.kind]).join(", "));
function visit(node) {
if (ts.isPropertyAccessExpression(node) &&
node.expression.getText(source) === "result") {
const symbol = checker.getSymbolAtLocation(node.expression);
const receiver = checker.getTypeAtLocation(node.expression);
const property = checker.getTypeAtLocation(node);
console.log(
node.getText(source),
"|", symbol.getName(),
"|", checker.typeToString(receiver),
"|", checker.typeToString(property)
);
}
if (ts.isCallExpression(node) && node.expression.getText(source) === "unwrap") {
console.log(checker.signatureToString(checker.getResolvedSignature(node)));
}
ts.forEachChild(node, visit);
}
visit(source);TypeAliasDeclaration, FunctionDeclaration, FunctionDeclaration
result.ok | result | Result<T> | boolean
result.value | result | { ok: true; value: T; } | T
(result: Result<number>, fallback: number): numberThe two property accesses share the parameter symbol, but the type query sees a union in one location and a single member in the other. The last line shows the instantiated signature with number everywhere the generic signature used T. Neither of those conclusions requires the compiler to execute the example.
Move the property read out of the guard and run the queries again. In the Undefined Stack checkout, the following commands reproduce the internal flow and inference evidence. The probe is pinned to the 6.0.3 implementation because its checkpoint is inside a private compiler function.
node --input-type=module -e '
import { captureFlowCases } from "./src/dives/typescript/flow.ts";
for (const entry of captureFlowCases()) {
console.log(entry.label, entry.receiver);
console.log(entry.graph);
}
'
node src/dives/typescript/trace-inference.mjs
node --test src/dives/typescript/flow.test.mjsThen inspect the native implementation. Start with declareSymbol for the declaration, getFlowTypeOfReference for the type of the receiver and inferTypeArguments for the resolved call. Each function answers a question you can already reproduce in the small program.
JavaScript Compiler API guide · Binder · Flow analysis · Checker
End of TypeScript compiler · 8 levels, Idea to Runtime
Where to next
Next in Languages and runtimes · 02 of 08
What V8 does with your JavaScript
One distance function, four execution tiers, and an assumption that breaks. Step through real bytecode, build hidden classes, feed an inline cache, and follow a deoptimization down to the machine instructions that caused it.