TypeScript 里几个天天在用的类型技巧
1. satisfies 代替 as
const config = { port: 3000 } satisfies Config保留字面量推导的同时做类型检查,比 as 安全。
2. 模板字面量类型
type Route = `/app/${string}`
const r: Route = '/app/notes'API 路由定义一次成型,typo 直接编译报错。
3. discriminated union
type State =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'error'; message: string }switch 收窄后每个分支的类型都是确定的,状态机写起来非常踏实。