TypeScript 的这些类型技巧,用了就回不去
写 TS 两年,挑几个日常用得最多的。
1. satisfies 替代类型断言
const routes = { home: '/', about: '/about' } satisfies Record<string, string>;
既校验类型,又保留字面量类型,as 做不到。
2. 模板字面量类型
type Event = `on${Capitalize<'click' | 'focus'>}`; // onClick | onFocus
3. infer 提取类型
type ReturnOf<T> = T extends (...args: any[]) => infer R ? R : never;
4. Partial / Pick / Omit 组合拳
接口字段太多时,别手写一遍,用内置工具类型。
5. as const
配置数组、枚举集合,加了 as const 类型才精确。
6. 类型收窄
if (typeof x === 'string') { ... }
利用 TS 的控制流分析,别动不动就 ! 或 as any。
最重要的一条
尽量别用 any,它是类型系统的逃生舱,用多了等于没写。要用就 unknown 然后自己收窄。