TypeScript symbols exist in two distinct spaces: Type Space and Value Space. Symbols in the type space are used for static type checking and are erased during compilation to JavaScript. Symbols in the value space exist at runtime.
Key distinctions:
- Type Space: Introduced by
type and interface. These are erased at runtime. - Value Space: Introduced by
const, let, var, or function implementations. These persist in the compiled JavaScript. - Dual Space:
class and enum introduce both a type (based on the structure) and a value (the constructor function or the enum object).
Context determines which space a symbol belongs to:
- Symbols following a colon (
:) or the as keyword are in the type space. - Symbols following an assignment operator (
=) are in the value space.
interface Person { // Type Space
first: string
last: string
}
const jane: Person = { first: 'Jane', last: 'Jacobs' }
// ^ Value Space ^ Type Space ^ Value Space