在 TypeScript 中,联合类型(Union Types)和交叉类型(Intersection Types)是两种用于组合类型的强大工具。它们允许你创建更复杂和灵活的类型,以满足不同的需求。
联合类型(Union Types)
联合类型表示一个值可以是多种类型之一。使用 |
符号将多个类型组合在一起,表示该值可以是其中任意一种类型。
语法
type UnionType = Type1 | Type2 | Type3;
示例
以下是一个简单的联合类型示例,展示了如何定义一个可以是 string
或 number
类型的变量:
let value: string | number;
value = "hello"; // OK
value = 42; // OK
value = true; // Error: Type 'boolean' is not assignable to type 'string | number'.
在这个例子中,value
可以是 string
或 number
类型,但不能是其他类型。
使用场景
- 处理多种类型的输入:当你需要处理多种类型的输入时,可以使用联合类型。
- 类型保护:通过类型保护(如
typeof
、instanceof
或用户定义的类型保护函数),可以在运行时确定具体的类型。
function printValue(value: string | number) {
if (typeof value === "string") {
console.log(`String value: ${value}`);
} else {
console.log(`Number value: ${value}`);
}
}
printValue("hello"); // 输出: String value: hello
printValue(42); // 输出: Number value: 42
交叉类型(Intersection Types)
交叉类型表示一个值必须同时满足多个类型的条件。使用 &
符号将多个类型组合在一起,表示该值必须具有所有类型的属性和方法。
语法
type IntersectionType = Type1 & Type2 & Type3;
示例
以下是一个简单的交叉类型示例,展示了如何定义一个同时具有 Person
和 Employee
属性的对象:
interface Person {
name: string;
age: number;
}
interface Employee {
employeeId: number;
department: string;
}
type EmployeePerson = Person & Employee;
const employee: EmployeePerson = {
name: "Alice",
age: 25,
employeeId: 1234,
department: "HR"
};
在这个例子中,EmployeePerson
类型必须同时具有 Person
和 Employee
接口的所有属性。
使用场景
- 组合多个类型:当你需要组合多个类型的属性和方法时,可以使用交叉类型。
- 扩展类型:通过交叉类型,可以扩展现有类型,创建更复杂的类型。
interface Printable {
print(): void;
}
interface Loggable {
log(): void;
}
function createLogger(): Printable & Loggable {
return {
print() {
console.log("Printing...");
},
log() {
console.log("Logging...");
}
};
}
const logger = createLogger();
logger.print(); // 输出: Printing...
logger.log(); // 输出: Logging...
联合类型与交叉类型的区别
特性 |
联合类型(Union Types) |
交叉类型(Intersection Types) |
表示 |
一个值可以是多种类型之一 |
一个值必须同时满足多个类型的条件 |
符号 |
` |
` |
使用场景 |
处理多种类型的输入 |
组合多个类型的属性和方法 |
类型保护 |
需要类型保护来确定具体类型 |
不需要类型保护,值必须满足所有类型 |
总结
联合类型和交叉类型是 TypeScript 中用于组合类型的两种强大工具。联合类型表示一个值可以是多种类型之一,而交叉类型表示一个值必须同时满足多个类型的条件。理解它们的使用场景和语法,可以帮助你编写出更灵活、更类型安全的代码。