Sub topic 3
How TypeScript Compiles: Checking First, Types Erased
Assume you know JavaScript functions, objects, and modules, and that Node.js and npm are installed. You will also need basic terminal commands. This chapter focuses on what happens between a .ts source file and the JavaScript that runs.
The compilation model
TypeScript adds a static type system to JavaScript. Static means that TypeScript checks types before the program runs. The TypeScript compiler, usually called tsc, performs two related jobs:
- It checks the source code for type errors.
- It emits JavaScript that a runtime such as Node.js or a browser can execute.
TypeScript types help the compiler understand your intent. They are not normally part of the JavaScript output.
function formatUser(name: string, age: number): string {
return `${name} is ${age} years old.`;
}
const message = formatUser("Ada", 36);
console.log(message);The compiler checks that name is a string, age is a number, and the function returns a string. The emitted JavaScript is similar to this:
function formatUser(name, age) {
return `${name} is ${age} years old.`;
}
const message = formatUser("Ada", 36);
console.log(message);The : string and : number annotations have disappeared. This removal is called type erasure. The types guide development and compilation, but they do not validate values at runtime.
Checking happens before emit
Consider a call with the wrong argument type:
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Ada"));
// console.log(greet(42)); // Error: number is not assignable to stringIf you uncomment the second call, tsc reports an error. Depending on your compiler settings, it might still write JavaScript. The generated JavaScript cannot enforce the annotation because the annotation no longer exists:
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet(42));The JavaScript runtime accepts the call. TypeScript's protection existed during compilation, not during execution.
What types can and cannot do
TypeScript can find many mistakes before execution:
- Passing a number where a function expects a string.
- Reading a property that is not declared on an object type.
- Forgetting that a value might be
undefined. - Returning the wrong type from a function.
TypeScript cannot guarantee that runtime data matches its declared type. This code compiles because the assertion tells TypeScript to trust the programmer:
const rawValue: unknown = JSON.parse('{"name":"Ada"}');
const user = rawValue as { name: string };
console.log(user.name);The as expression changes the compiler's view of the value. It does not inspect the object or add a runtime check. If the parsed value has no name property, the program can still fail or produce an incorrect result.
A compile pipeline
The compiler processes a TypeScript file in stages.
Parsing finds syntax problems such as an incomplete function. Type checking compares values, parameters, properties, and return types. If those stages succeed, or if emit is allowed despite diagnostics, tsc produces JavaScript according to the configured target and module format.
Checking is separate from running
A successful type check does not mean the program has run. It only means that the compiler found no errors under the selected rules. Likewise, code can run while still containing type errors if a separate tool transpiles it without performing full type checking.
Exercise
Why can greet(42) be rejected by TypeScript even though the emitted JavaScript can still call greet(42)?
Show answer
TypeScript checks the call before emit, but it erases the parameter type during compilation. JavaScript receives no runtime type enforcement from the annotation.