TypeScript Reference ยท Concepts and Comparisons
Type erasure in TypeScript
Why TypeScript types vanish when code is compiled, what you cannot do with them at run time, and which constructs emit real JavaScript.
TypeScript checks types while compiling and then removes them. The JavaScript that runs contains no interfaces, no type aliases, no generics and no annotations. That is type erasure.
The consequence is simple but easy to forget: a type is not a value. You cannot test x instanceof Point when Point is an interface, loop over the members of a union, or ask a generic function what T is. If you need information at run time, it must exist as a real value.
interface User { name: string } // if (value instanceof User) {} // error TS2693: 'User' only refers to a type
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
What is erased and what is kept
| Construct | At run time |
|---|---|
Type annotations, interface, type |
Removed completely |
| Generics and type arguments | Removed |
as, satisfies, !, <T> assertions |
Removed (the plain expression stays) |
import type / export type |
Removed |
declare statements |
Removed |
| Classes | Kept as JavaScript classes |
Regular enum |
Kept as an object |
const enum |
Inlined (without isolatedModules) |
| Namespaces with values | Kept as an object |
| Parameter properties | Become assignments in the constructor |
Working with erasure
- Check shapes with real code. Use type guards,
in,typeof, discriminant fields or a validation library; see Runtime validation. - Pass a value when you need a type. A constructor argument or a schema object carries what
Tcannot. - Overloads exist only in the type system; the single implementation must inspect its arguments.
- Casts do not convert.
"5" as unknown as numberstill holds a string. - JSON from outside is
anyorunknown; the declared type is a hope until it is checked.
Usage notes
- Erasable syntax only:
erasableSyntaxOnlybans features that emit code, so Node can strip types directly; see erasableSyntaxOnly. - Node type stripping relies on erasure: removing the types leaves valid JavaScript.
- Decorators and metadata are the exception: the legacy emit-metadata option records some type information as values.
- Bundle size is unaffected by type-only code, but non-type-only imports of types can keep a module alive; use
import type.