返回

TypeScript 类型系统揭秘:联合类型、交叉类型与类型保护

前端

联合类型

联合类型是一种可以表示多个类型的类型。联合类型的语法是 T1 | T2 | ... | Tn,其中 T1T2、...、Tn 是多个类型。联合类型的值可以是 T1T2、...、Tn 中的任意一种类型。

联合类型是使用 | 运算符来声明的。例如,我们可以声明一个 Animal 类型的变量,它的值可以是 DogCatFish

type Animal = Dog | Cat | Fish;

交叉类型

交叉类型是一种可以表示多个类型的交集的类型。交叉类型的语法是 T1 & T2 & ... & Tn,其中 T1T2、...、Tn 是多个类型。交叉类型的值必须同时是 T1T2、...、Tn 中的类型。

交叉类型是使用 & 运算符来声明的。例如,我们可以声明一个 Dog 类型的变量,它必须同时是 AnimalMammal 类型的。

type Dog = Animal & Mammal;

类型保护

类型保护是一种检查变量类型的机制。类型保护可以帮助我们确保变量的值是某种类型。类型保护有几种不同的方式,包括:

  • 类型断言
  • 类型别名
  • instanceof 运算符
  • in 运算符

类型断言

类型断言是一种显式地告诉 TypeScript 变量的类型的机制。类型断言的语法是 variable as type,其中 variable 是变量名,type 是变量的类型。

例如,我们可以使用类型断言来告诉 TypeScript animal 变量的值是 Dog 类型的。

const animal: Animal = new Dog();
const dog = animal as Dog;

类型别名

类型别名是一种给类型起别名的机制。类型别名的语法是 type alias = type,其中 alias 是别名,type 是类型的名称。

例如,我们可以使用类型别名来给 Dog 类型起一个别名 Canine

type Canine = Dog;

instanceof 运算符

instanceof 运算符可以检查一个变量是否是某个类型的实例。instanceof 运算符的语法是 variable instanceof type,其中 variable 是变量名,type 是类型的名称。

例如,我们可以使用 instanceof 运算符来检查 animal 变量的值是否是 Dog 类型的。

const animal: Animal = new Dog();
if (animal instanceof Dog) {
  // animal 是 Dog 类型的
}

in 运算符

in 运算符可以检查一个属性或方法是否属于某个类型。in 运算符的语法是 property in type,其中 property 是属性或方法的名称,type 是类型的名称。

例如,我们可以使用 in 运算符来检查 speak 方法是否属于 Animal 类型。

if ('speak' in Animal) {
  // Animal 类型具有 speak 方法
}

总结

联合类型、交叉类型和类型保护是 TypeScript 中三个重要的概念。联合类型可以表示多个类型的集合,交叉类型可以表示多个类型的交集,类型保护可以检查变量的类型。这三个概念可以帮助我们更好地理解和使用 TypeScript 的类型系统。