Type erasure and emit
Concept and syntax
Type annotations help the checker but are erased from emitted JavaScript. Compare const rate: number = 3 with the emitted const rate = 3. Compile with the command from the first program lesson and inspect main.js. typeof rate at runtime asks JavaScript about the value, not the removed annotation. Some TypeScript constructs such as enums can generate runtime code; the erasure rule here concerns type-only syntax, not every TypeScript feature.
Working example
Compile standalone examples in a fresh directory with tsc --strict --target ES2022 --module commonjs --noEmitOnError main.ts, then node main.js.
const rate: number = 3;function fee(n: number): number { return n * rate; }console.log(fee(4), typeof rate);Expected output (one line per log):
12 numberconst rate = 3;function fee(n) { return n * rate; }console.log(fee(4), typeof rate);Common mistake
Intentionally invalid; check this snippet separately. Do not run it.
Expected compiler diagnostic: TS2322. A type annotation does not convert a string into a number. Correct the value or explicitly convert it and validate the result.
Practice and recap
Compile the valid example, inspect main.js and identify which tokens disappeared. Change the rate to 4 and predict the output.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Type erasure and emit — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
What remains in emitted JavaScript from const rate: number = 3?
What does typeof rate inspect when the program runs?
Why does : number not make this initializer valid?
const rate: number = "3";