类型 Erasure
一句话解释
类型 erasure 是处理通过哪个 TypeScript 编译器移除所有类型 annotations, 接口, and 类型 aliases, producing plain JavaScript 使用否 类型信息.
用大白话说
Type erasure means all TypeScript type information is removed when compiling to JavaScript. Type annotations, interfaces, type aliases, generics, and utility types are all erased — the output is plain JavaScript.
这个是why TypeScript types cannot be checked at runtime。 If you need runtime type information, you must use enums (which compile to objects), classes (which compile to JS classes), or runtime validation libraries like zod or io-ts.
Type erasure is a fundamental design decision: it keeps the JavaScript output clean and performant, and ensures TypeScript is a strict superset of JavaScript. The tradeoff is that types are a compile-time-only concept.
示例
// TypeScript input
let x: number = 5;
interface User { name: string; }
// JavaScript output (after erasure)
let x = 5;
// interface User is gone所有类型 annotations and 接口是 移除 in JavaScript 输出.
相关术语
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。