TypeScript 联合类型和交叉类型
TypeScript 提供了强大的类型系统功能,可帮助您编写更安全、更可预测的代码。这些功能包括并集和交集类型,它们在定义和管理复杂类型方面提供了灵活性。本文介绍了这些概念,并提供了示例来说明它们的用法。
什么是联合类型?
联合类型允许变量保存不同类型的值。当您需要表示可能属于多种类型的值时,这很有用。联合类型使用 |
(管道)符号表示。
定义联合类型
要定义联合类型,需要指定由 |
符号分隔的多个类型:
let value: string | number;
value = "Hello, TypeScript"; // Valid
value = 42; // Valid
value = true; // Error: Type 'boolean' is not assignable to type 'string | number'
在这个例子中,变量 value
可以是 string
或 number
,但不能是 boolean
。
在函数中使用联合类型
联合类型在参数或返回类型可以是多种类型的函数中特别有用:
function formatValue(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase();
} else {
return value.toFixed(2);
}
}
console.log(formatValue("hello")); // Output: HELLO
console.log(formatValue(123.456)); // Output: 123.46
formatValue
函数接受一个参数,该参数可以是 string
或 number
,并对其进行相应的格式化。
交叉口类型有哪些?
交集类型允许您将多个类型合并为一个。这意味着交集类型的值将满足交集中的所有类型。交集类型使用 &
(与号)符号表示。
定义交叉口类型
要定义交叉类型,请指定由 &
符号分隔的多个类型:
interface Person {
name: string;
}
interface Employee {
employeeId: number;
}
type EmployeePerson = Person & Employee;
const john: EmployeePerson = {
name: "John Doe",
employeeId: 1234
};
console.log(john.name); // Output: John Doe
console.log(john.employeeId); // Output: 1234
在此示例中,EmployeePerson
类型结合了 Person
和 Employee
接口,从而产生了同时具有 name
和 employeeId
属性的类型。
在函数中使用交叉类型
交叉类型也可以在函数中使用来要求多个类型属性:
function printEmployeeDetails(employee: Person & Employee): void {
console.log(`Name: ${employee.name}`);
console.log(`Employee ID: ${employee.employeeId}`);
}
const jane: EmployeePerson = {
name: "Jane Smith",
employeeId: 5678
};
printEmployeeDetails(jane);
// Output:
// Name: Jane Smith
// Employee ID: 5678
printEmployeeDetails
函数需要一个同时满足 Person
和 Employee
类型的参数。
结合并集和交集类型
您可以组合联合类型和交集类型来创建复杂的类型定义:
type Shape = Circle | Rectangle;
interface Circle {
kind: "circle";
radius: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
function getArea(shape: Shape): number {
if (shape.kind === "circle") {
return Math.PI * shape.radius * shape.radius;
} else {
return shape.width * shape.height;
}
}
const myCircle: Circle = { kind: "circle", radius: 10 };
const myRectangle: Rectangle = { kind: "rectangle", width: 20, height: 30 };
console.log(getArea(myCircle)); // Output: 314.159...
console.log(getArea(myRectangle)); // Output: 600
在这个例子中,Shape
类型是 Circle
和 Rectangle
的联合,并且 getArea
函数相应地处理这两种类型。
结论
TypeScript 中的联合类型和交集类型提供了管理和组合类型的强大方法,在类型定义中提供了灵活性和精确性。联合类型允许变量为多种类型之一,而交集类型则将多种类型合并为一种。通过使用这些功能,您可以创建更强大且类型安全的应用程序。
练习使用联合类型和交集类型以熟悉它们的功能并提高您的 TypeScript 编码技能。