Type 与联合/交叉类型
约 330 字大约 1 分钟
布欧-Lewyon
2026-05-16
首页 › TypeScript › 接口与类型别名 › Type 与联合/交叉类型
联合类型
type Status = 'active' | 'inactive' | 'pending';
type ID = string | number;
type Result = { success: true; data: any } | { success: false; error: string };类型收窄
function printId(id: string | number) {
// typeof 收窄
if (typeof id === 'string') {
console.log(id.toUpperCase()); // 此块内 id 是 string
} else {
console.log(id.toFixed(2)); // 此块内 id 是 number
}
}
// 字面量收窄
function process(status: 'active' | 'inactive') {
if (status === 'active') {
console.log('激活');
}
}
// in 收窄
interface Fish { swim(): void; }
interface Bird { fly(): void; }
function move(animal: Fish | Bird) {
if ('swim' in animal) {
animal.swim();
}
}可辨识联合(Discriminated Union)
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'rectangle'; width: number; height: number }
| { kind: 'triangle'; base: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle': return Math.PI * shape.radius ** 2;
case 'rectangle': return shape.width * shape.height;
case 'triangle': return shape.base * shape.height / 2;
}
}交叉类型
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;
const p: Person = { name: '张三', age: 28 };
// 同名属性冲突
type A = { id: string };
type B = { id: number };
type C = A & B; // id: string & number → never小结
| 类型 | 语法 | 场景 |
|---|---|---|
| 联合 | A | B | 值可能是多种类型之一 |
| 交叉 | A & B | 合并多个类型的全部属性 |
| 可辨识联合 | kind 字段区分 | 状态机、处理不同类型的统一函数 |
上一节:Interface 详解 下一节:字面量类型与索引签名
