三块面板:TS 源码 / 写死的 tsc 报错样本(非现场运行)/ 可点跑的等价 JS。核心:TS 里一个具体值本身就是一种类型,白名单错误在写的时候就暴露。
type Dir = 'up' | 'down' | 'left' | 'right'
function move(d: Dir) { /* 只认这四个 */ }
move('up') // ✓
move('diagonal') // ✗ 不在白名单,写的时候就报错
as constconst a = { dir: 'up' } // dir: string(被宽化)
const b = { dir: 'up' } as const // dir: 'up'(钉死),且整个对象只读
const arr = [1, 2] as const // readonly [1, 2]
typeof + 索引访问const CONFIG = { api: '/v1', retry: 3 } as const
type ConfigKey = keyof typeof CONFIG // 'api' | 'retry'
type RetryVal = (typeof CONFIG)['retry'] // 3(把值当类型取出来)
const Direction = { Up: 0, Down: 1, Left: 2 } as const
type Direction = (typeof Direction)[keyof typeof Direction] // 0 | 1 | 2
function go(d: Direction) { /* d 只能是 0 | 1 | 2 */ }
go(Direction.Up) // ✓
go(9) // ✗ 9 不在联合里