TypeScript 基础指南:类型守卫(Type Guards)和 类型区分(Differentiating Types)

类型守卫(Type Guards)和 类型区分(Differentiating Types)是 TypeScript 中用于处理联合类型(Union Types)的两个重要概念。

部分
1
类型守卫(Type Guards)

类型守卫(Type Guards)是一种类型检查机制,它可以在运行时缩小变量的类型范围。TypeScript 编译器可以利用 Type Guards 来提高类型安全性和代码可读性。 Type Guards 通常通过以下方式实现:

typeof 检查:
function printLength(input: string | number) {
  if (typeof input === 'string') {
    console.log(input.length); // input 在这里被缩小为 string 类型
  } else {
    console.log(input.toFixed(2)); // input 在这里被缩小为 number 类型
  }
}
instanceof 检查:
class Animal { name: string; }
class Dog extends Animal { breed: string; }

function getSound(animal: Animal) {
  if (animal instanceof Dog) {
    console.log(`The ${animal.breed} dog says: Woof!`);
  } else {
    console.log(`The ${animal.name} says: Some sound.`);
  }
}
自定义类型谓词:
function isDog(animal: Animal): animal is Dog {
  return (animal as Dog).breed !== undefined;
}

function getSound(animal: Animal) {
  if (isDog(animal)) {
    console.log(`The ${animal.breed} dog says: Woof!`);
  } else {
    console.log(`The ${animal.name} says: Some sound.`);
  }
}
部分
2
类型区分(Differentiating Types)

类型区分(Differentiating Types)是指在处理联合类型时,根据变量的实际类型执行不同的逻辑。这通常通过 Type Guards 配合 switch 语句或 if-else 语句来实现。 例如:

interface Square {
  kind: 'square';
  size: number;
}

interface Rectangle {
  kind: 'rectangle';
  width: number;
  height: number;
}

interface Circle {
  kind: 'circle';
  radius: number;
}

type Shape = Square | Rectangle | Circle;

function calculateArea(shape: Shape) {
  switch (shape.kind) {
    case 'square':
      return shape.size * shape.size;
    case 'rectangle':
      return shape.width * shape.height;
    case 'circle':
      return Math.PI * shape.radius ** 2;
  }
}

在这个例子中,我们定义了一个联合类型 Shape,它可以是 Square、Rectangle 或 Circle 类型。在 calculateArea 函数中,我们使用 switch 语句根据 shape.kind 属性来区分不同的类型,并执行相应的计算逻辑。 通过 Type Guards 和 Differentiating Types,TypeScript 可以在编译时和运行时更好地处理联合类型,提高代码的类型安全性和可读性。