摘要:在本教程中,您将学习 TypeScript 交集类型,通过组合多个现有类型来创建新的类型。
TypeScript 交集类型的介绍
交集类型通过组合多个现有类型来创建一个新的类型。新类型具有现有类型的所有特征。
要组合类型,请使用 &
运算符,如下所示
type typeAB = typeA & typeB;
Code language: TypeScript (typescript)
typeAB
将具有 typeA
和 typeB
的所有属性。
请注意,联合类型使用 |
运算符,它定义了一个可以保存 typeA
或 typeB
值的变量。
let varName = typeA | typeB; // union type
Code language: TypeScript (typescript)
假设您有三个接口:BusinessPartner
、Identity
和 Contact
。
interface BusinessPartner {
name: string;
credit: number;
}
interface Identity {
id: number;
name: string;
}
interface Contact {
email: string;
phone: string;
}
Code language: TypeScript (typescript)
下面定义了两个交集类型
type Employee = Identity & Contact;
type Customer = BusinessPartner & Contact;
Code language: TypeScript (typescript)
Employee
类型包含 Identity
和 Contact
类型的全部属性
type Employee = Identity & Contact;
let e: Employee = {
id: 100,
name: 'John Doe',
email: '[email protected]',
phone: '(408)-897-5684'
};
Code language: TypeScript (typescript)
Customer
类型包含 BusinessPartner
和 Contact
类型的全部属性
type Customer = BusinessPartner & Contact;
let c: Customer = {
name: 'ABC Inc.',
credit: 1000000,
email: '[email protected]',
phone: '(408)-897-5735'
};
Code language: TypeScript (typescript)
之后,如果您想实现员工销售,您可以创建一个包含 Identity
、Contact
和 BusinessPartner
类型的所有属性的新交集类型
type Employee = Identity & BusinessPartner & Contact;
let e: Employee = {
id: 100,
name: 'John Doe',
email: '[email protected]',
phone: '(408)-897-5684',
credit: 1000
};
Code language: TypeScript (typescript)
请注意,BusinessPartner
和 Identity
都具有相同类型的 name
属性。如果它们不相同,那么您将收到错误。
类型顺序
当您交叉类型时,类型的顺序无关紧要。例如
type typeAB = typeA & typeB;
type typeBA = typeB & typeA;
Code language: TypeScript (typescript)
在此示例中,typeAB
和 typeBA
具有相同的属性。
总结
- 交集类型将两个或多个类型组合在一起,以创建一个具有现有类型所有属性的新类型。
- 组合类型时,类型顺序并不重要。
本教程对您有帮助吗?