字面量类型与联合类型
字面量类型、联合类型与类型缩窄
1. 字面量类型
type Direction = 'left' | 'right' | 'up' | 'down';
type HTTPStatus = 200 | 301 | 404 | 500;
type True = true;
2. 联合类型
type ID = string | number;
// 可辨识联合
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; size: number }
| { kind: 'rectangle'; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'square':
return shape.size ** 2;
case 'rectangle':
return shape.width * shape.height;
}
}
3. 类型缩窄
// typeof / instanceof / in / 赋值缩窄
function pad(value: string | number) {
if (typeof value === 'string') return value.toUpperCase();
return value.toFixed(2);
}
// 可辨识联合缩窄
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function move(animal: Fish | Bird) {
if ('swim' in animal) animal.swim();
else animal.fly();
}
4. 模板字面量类型
type EventName = `on${Capitalize<string>}`;
type CSSValue = `${number}${'px' | 'em' | 'rem'}`;