类型收窄
function format(value: string | number) {
if (typeof value === 'string') {
return value.toUpperCase(); // TS 知道这里是 string
}
return value.toFixed(2); // TS 知道这里是 number
}
收窄方式
| 方式 | 适用 | 示例 |
|---|
| typeof | 原始类型 | typeof x === 'string' |
| instanceof | 类实例 | x instanceof Date |
| in | 属性检查 | 'name' in x |
| Array.isArray | 数组 | Array.isArray(x) |
| 自定义守卫 | 复杂类型 | function isUser(x): x is User |
Discriminated Union
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'rect'; width: number; height: number };
function area(s: Shape) {
switch (s.kind) {
case 'circle': return Math.PI * s.radius ** 2;
case 'rect': return s.width * s.height;
}
}
Discriminated Union 是 React 组件 props 的常用模式。