title: 交叉类型

交叉类型

原文地址

在本教程中,你将学习 TypeScript 中的交叉类型。

TypeScript 中的交叉类型介绍

交叉类型指的是通过组合多个现有类型创建而来的新的类型,新的类型具有现有类型的所有属性。

使用 & 操作符来表示组合类型,如下所示:

  1. type typeAB = typeA & typeB;

typeAB 会有 typeAtypeB 的所有属性。

注意,联合类型使用 | 操作符,定义一个可以保存 typeA 或者 typeB 类型的值。

  1. let varName = typeA | typeB; // union type

假设你有三个接口:BusinessPartner, IdentityContact

  1. interface BusinessPartner {
  2. name: string;
  3. credit: number;
  4. }
  5. interface Identity {
  6. id: number;
  7. name: string;
  8. }
  9. interface Contact {
  10. email: string;
  11. phone: string;
  12. }

下面定义了两个交叉类型:

  1. type Employee = Identity & Contact;
  2. type Customer = BusinessPartner & Contact;

Employee 类包含 IdentityContact 类型中的所有属性:

  1. type Employee = Identity & Contact;
  2. let e: Employee = {
  3. id: 100,
  4. name: 'John Doe',
  5. email: 'john.doe@example.com',
  6. phone: '(408)-897-5684',
  7. };

Customer 类型包含 BusinessPartnerContact 类型中的所有属性:

  1. type Customer = BusinessPartner & Contact;
  2. let c: Customer = {
  3. name: 'ABC Inc.',
  4. credit: 1000000,
  5. email: 'sales@abcinc.com',
  6. phone: '(408)-897-5735',
  7. };

之后,如果你想实现销售员工,你可以创建一个新的交叉类型,它包含 Identity, ContactBusinessPartner 三个接口中的所有属性:

  1. type Employee = Identity & BusinessPartner & Contact;
  2. let e: Employee = {
  3. id: 100,
  4. name: 'John Doe',
  5. email: 'john.doe@example.com',
  6. phone: '(408)-897-5684',
  7. credit: 1000,
  8. };

注意 BusinessPartnerIdentity 有相同类型的 name 属性,如果它们类型不同,编译器会抛出一个错误提示。

类型顺序

类型交叉中的类型的顺序并不重要,如下所示:

  1. type typeAB = typeA & typeB;
  2. type typeBA = typeB & typeA;

在这个例子中,typeABtypeBA 有着相同的属性,它们是等价的。

小结

  • 交叉类型可以结合两个或者更多的类型,创建具有所有类型的属性的新类型;
  • 类型交叉中的类型的顺序并不重要。