Sub topic 3
How TypeScript compiles: checking first, types erased
This chapter explains what tsc does between your .ts file and the JavaScript that runs. It assumes you can read JavaScript with modules, you can use a terminal, and you know that TypeScript adds type annotations to JavaScript. You do not need to have installed the compiler yet. The next chapters cover installation and configuration.
The model has two parts. The compiler first checks your program against its types. It then emits JavaScript with every type removed. These two jobs are separate, and most surprises in day-to-day TypeScript come from forgetting that.
The pipeline from source to JavaScript
tsc processes each file in stages. The names below are the compiler's own terms.
- Parse. The source text becomes an abstract syntax tree (AST), a tree of nodes that represents the program's structure.
- Bind. The compiler builds symbols, which link each name to its declaration.
- Check. The type checker computes the type of each expression and reports mismatches as diagnostics.
- Emit. The compiler writes JavaScript, and optionally
.d.tsdeclaration files and source maps.
Checking does not change the program. It only produces messages. Emit does not need the checker's verdict. In the default configuration tsc writes JavaScript even when the checker found errors.
What type erasure means
Type erasure means that type annotations exist only at compile time. The emitted JavaScript contains none of them, and the running program has no knowledge of them.
Here is a small program with an interface and annotations.
interface User {
id: number;
name: string;
}
function describe(user: User): string {
return `${user.id}: ${user.name}`;
}
console.log(describe({ id: 1, name: "Ada" }));With target set to ES2022, the emitted file looks like this.
function describe(user) {
return `${user.id}: ${user.name}`;
}
console.log(describe({ id: 1, name: "Ada" }));The User interface is gone, along with the : User and : string annotations. Nothing in the output checks that user has an id or a name. The interface helped you write correct code, and then it disappeared.
Consequences for runtime code
Because types are erased, you cannot use them in runtime expressions. This code does not compile.
interface User {
id: number;
name: string;
}
function isUser(value: unknown): boolean {
return value instanceof User;
}The compiler reports that User only refers to a type but is being used as a value. instanceof needs a constructor function that exists at runtime, and an interface is not one. To test a shape at runtime, write a function that inspects the value. Declaring its return type as a type predicate (value is User) tells the checker what a true result means.
interface User {
id: number;
name: string;
}
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
typeof (value as { id?: unknown }).id === "number" &&
typeof (value as { name?: unknown }).name === "string"
);
}
const parsed: unknown = JSON.parse('{"id": 1, "name": "Ada"}');
if (isUser(parsed)) {
console.log(parsed.name.toUpperCase());
} else {
console.log("Not a user");
}The typeof and in-style checks are real JavaScript that survives erasure. The value is User annotation is erased, and it only informs the checker.
Types are promises, not guarantees
The checker verifies that your code is consistent with the types you declared. It cannot verify that data arriving at runtime matches them. JSON.parse returns any, and network responses, files, and environment variables are all untyped at the boundary. A type assertion such as JSON.parse(text) as User tells the compiler to trust you, and it emits no check at all.
Checking and emitting are separate decisions
Run this on a file with a type error.
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet(42));tsc prints error TS2345 because number is not assignable to string. By default it still writes the JavaScript file. The process exits with code 2, which means diagnostics were reported and output was generated. Running the emitted JavaScript prints Hello, 42!, because JavaScript does not care.
Two compiler options change this behavior:
| Option | Effect | Exit code on a type error |
|---|---|---|
| (default) | Reports errors and still emits JavaScript | 2 |
| `noEmitOnError` | Reports errors and writes no files | 1 |
| `noEmit` | Checks only and never writes JavaScript | 1 |
Use noEmitOnError when you want a failed build to leave no new output behind. Use noEmit when something else produces the JavaScript. The later chapters on emit control and build tools return to both.
What emit changes besides removing types
Erasing types is only part of emit. The compiler also rewrites some syntax, depending on your options.
- Downleveling. The
targetoption sets the JavaScript version of the output. Withtarget: ES5,asyncfunctions and template strings are rewritten into older constructs. WithES2022they pass through unchanged. - Module conversion. The
moduleoption decides whetherimportandexportstay as ES modules or become CommonJSrequirecalls. - Import elision. An import used only as a type is dropped from the output. This can matter when a module has side effects you were counting on. The
verbatimModuleSyntaxoption makes elision explicit. It requiresimport typefor type-only imports and keeps every other import as written.
Neither target nor module adds missing library features. Setting target: ES5 does not give old runtimes a Promise or Array.prototype.includes. The lib option controls which built-in types the checker knows about. Polyfills are your responsibility.
Syntax that is not erased
A few TypeScript features generate JavaScript code, so they are not pure type annotations. An enum is the common example.
enum Color {
Red,
Green,
}
console.log(Color.Green);This emits a real object, built by an immediately invoked function.
var Color;
(function (Color) {
Color[Color["Red"] = 0] = "Red";
Color[Color["Green"] = 1] = "Green";
})(Color || (Color = {}));
console.log(Color.Green);Constructor parameter properties (constructor(private id: number)) and namespace blocks also emit code. Tools that only strip types cannot handle these without extra work. That is why some projects use a union of string literals instead of an enum, or turn on the erasableSyntaxOnly option in recent TypeScript versions. With that option, the compiler reports any syntax that needs more than deletion.
| Construct | Erased completely? |
|---|---|
| Type annotations, `interface`, `type` aliases | Yes |
| Generics, `as` assertions, `import type` | Yes |
| `enum`, `namespace` with values | No, emits an object |
| Parameter properties | No, emits assignments |
| Ordinary imports used as values | No, kept |
Why the separation matters in practice
Since emit does not depend on the checker's verdict, a tool can produce JavaScript without checking anything. Bundlers and runners such as esbuild, swc, and Babel's TypeScript preset do this. They delete the types file by file, which is very fast, but they never report a type error. Recent versions of Node can also run .ts files by stripping types.
A common setup combines the two roles:
- A fast tool transpiles the code for development or production.
tsc --noEmitruns in your editor, in a pre-commit hook, and in CI to do the checking.
Per-file tools cannot see other files, so they cannot resolve constructs that need cross-file type information. The isolatedModules option makes tsc warn about code that a per-file tool would mishandle. An example is re-exporting a type without marking it as one.
Common mistakes
- Expecting runtime checks. An annotated parameter does not validate its argument when the program runs. Check at the boundaries where data enters.
- Using a type as a value.
instanceof Interface,typeofcomparisons against type names, and iterating over a type all fail. Use a runtime value, such as a class, a constant array, or a type guard. - Treating a green build as proof.
any, assertions, and unchecked JSON can all pass the checker while the data is wrong. - Ignoring the exit code.
tsccan print errors and still write files. A script that only looks for output files will deploy broken code. - Assuming
targetadds features. It rewrites syntax, not the runtime library.
Exercise
You compile a file with npx tsc, and the checker reports one type error. You look in dist and find the JavaScript file was written. Why did that happen, and which option would prevent it?
Show answer
By default tsc checks and emits independently, so a type error does not stop JavaScript from being written. The exit code is 2 in this case. Setting noEmitOnError to true stops tsc from writing files when there are errors. The exit code then becomes 1.
Exercise
A teammate writes if (response instanceof ApiResponse) where ApiResponse is an interface, and the compiler rejects it. Explain why, and show a way to check the shape at runtime.
Show answer
Interfaces are erased during emit, so no ApiResponse value exists at runtime for instanceof to use. Write a type guard function such as function isApiResponse(v: unknown): v is ApiResponse that checks the properties with typeof and null checks. Those checks are ordinary JavaScript and survive erasure.
Exercise
Your project transpiles with esbuild. Why is it still useful to run tsc --noEmit, and what does each tool do?
Show answer
esbuild only strips types and emits JavaScript, and it never reports type errors. tsc --noEmit runs the full type checker and writes nothing, so it supplies the error checking that esbuild skips. Run it in the editor, in a pre-commit hook, and in CI.