关于前端:现代TypeScript高级教程类型守卫

3次阅读

共计 5010 个字符,预计需要花费 13 分钟才能阅读完成。

点击在线浏览,体验更好 链接
古代 JavaScript 高级小册 链接
深入浅出 Dart 链接
古代 TypeScript 高级小册 链接

类型守卫

概述

在 TypeScript 中,类型守卫能够用于在运行时查看变量的类型,并在代码块外部将变量的类型范畴放大到更具体的类型。这种类型收窄能够让 TypeScript 编译器更好地了解咱们代码的用意,从而提供更精确的类型推断和类型查看。

类型守卫通常应用类型断言、类型谓词、typeof 操作符、instanceof 操作符或自定义的谓词函数来判断变量的具体类型,并依据判断后果收窄变量的类型范畴。

typeof 类型守卫

typeof 类型守卫容许咱们应用 typeof 操作符来在代码中依据变量的类型范畴进行条件判断。以下是一个示例:

function printValue(value: string | number) {if (typeof value === 'string') {console.log(value.toUpperCase());
  } else {console.log(value.toFixed(2));
  }
}

printValue('hello');  // 输入: HELLO
printValue(3.1415);   // 输入: 3.14

在下面的示例中,咱们应用 typeof 操作符在条件语句中查看变量 value 的类型。如果它的类型是 'string',则调用 toUpperCase 办法;如果是 'number',则调用 toFixed 办法。通过应用 typeof 类型守卫,咱们可能依据不同的类型执行不同的代码逻辑。

instanceof 类型守卫

instanceof 类型守卫容许咱们应用 instanceof 操作符来查看对象的类型,并在代码块外部收窄对象的类型范畴。以下是一个示例:

class Animal {move() {console.log('Animal is moving');
  }
}

class Dog extends Animal {bark() {console.log('Dog is barking');
  }
}

function performAction(animal: Animal) {if (animal instanceof Dog) {animal.bark();
  } else {animal.move();
  }
}

const animal1 = new Animal();
const animal2 = new Dog();

performAction(animal1);  // 输入: Animal is moving
performAction(animal2);  // 输入: Dog is barking

在下面的示例中,咱们应用 instanceof 操作符在条件语句中查看变量 animal 的类型。如果它是 Dog 类的实例,则调用 bark 办法;否则调用 move 办法。通过应用 instanceof 类型守卫,咱们能够依据对象的具体类型执行不

同的代码逻辑。

应用自定义谓词函数类型守卫

自定义谓词函数类型守卫容许咱们定义本人的函数,依据特定条件判断变量的类型,并在代码块外部收窄变量的类型范畴。以下是一个示例:

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

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

type Shape = Circle | Rectangle;

function calculateArea(shape: Shape) {if (isCircle(shape)) {console.log(Math.PI * shape.radius ** 2);
  } else {console.log(shape.width * shape.height);
  }
}

function isCircle(shape: Shape): shape is Circle {return shape.kind === 'circle';}

const circle: Circle = {kind: 'circle', radius: 5};
const rectangle: Rectangle = {kind: 'rectangle', width: 10, height: 20};

calculateArea(circle);     // 输入: 78.53981633974483
calculateArea(rectangle);  // 输入: 200

在下面的示例中,咱们定义了 Shape 类型,它能够是 CircleRectangle。通过自定义的谓词函数 isCircle,咱们判断变量 shape 的类型是否是 Circle,并在条件语句外部收窄变量的类型范畴。通过应用自定义谓词函数类型守卫,咱们可能依据特定的谓词条件执行相应的代码逻辑。

联结类型守卫

类型守卫最罕用于联结类型中,因为联结类型可能蕴含多个不同的类型选项。以下是一个更简单的示例,展现了如何应用类型守卫和联结类型来提供更准确的类型推断和类型查看:

interface Car {
  type: 'car';
  brand: string;
  wheels: number;
}

interface Bicycle {
  type: 'bicycle';
  color: string;
}

interface Motorcycle {
  type: 'motorcycle';
  engine: number;
}

type Vehicle = Car | Bicycle | Motorcycle;

function printVehicleInfo(vehicle: Vehicle) {switch (vehicle.type) {
    case 'car':
      console.log(`Brand: ${vehicle.brand}, Wheels: ${vehicle.wheels}`);
      break;
    case 'bicycle':
      console.log(`Color: ${vehicle.color}`);
      break;
    case 'motorcycle':
      console.log(`Engine: ${vehicle.engine}`);
      break;
    default:
      const _exhaustiveCheck: never = vehicle;
  }
}

const car: Car = {type: 'car', brand: 'Toyota', wheels: 4};
const bicycle: Bicycle = {type: 'bicycle', color: 'red'};
const motorcycle: Motorcycle = {type: 'motorcycle', engine: 1000};

printVehicleInfo(car);         // 输入: Brand: Toyota, Wheels: 4
printVehicleInfo(bicycle);     // 输入: Color: red
printVehicleInfo(motorcycle);  // 输入: Engine: 1000

在下面的示例中,咱们定义了 Vehicle 类型,它是 CarBicycle 和 `Motor

cycle 的联结类型。通过应用 switch 语句和依据 vehicle.type 的不同值进行类型守卫,咱们能够在每个 case 分支中收窄 vehicle` 的类型范畴,并执行相应的代码逻辑。通过这种形式,咱们可能更精确地推断和查看联结类型的变量。

十分道歉之前的答复没有笼罩到你提到的其余重要概念。上面我将持续解析这些概念并提供相应的代码示例。

应用 in 操作符进行类型守卫

in 操作符能够用于在 TypeScript 中判断一个属性是否存在于对象中,从而进行类型判断和类型收窄。以下是一个示例:

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

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

type Shape = Circle | Rectangle;

function printArea(shape: Shape) {if ('radius' in shape) {console.log(Math.PI * shape.radius ** 2);
  } else {console.log(shape.width * shape.height);
  }
}

const circle: Circle = {kind: 'circle', radius: 5};
const rectangle: Rectangle = {kind: 'rectangle', width: 10, height: 20};

printArea(circle);     // 输入: 78.53981633974483
printArea(rectangle);  // 输入: 200

在下面的示例中,咱们应用 in 操作符来查看属性 'radius' 是否存在于 shape 对象中。如果存在,则收窄 shape 的类型为 Circle,并执行相应的代码逻辑。通过应用 in 操作符进行类型判断,咱们能够依据属性的存在与否进行类型收窄。

控制流类型守卫

在 TypeScript 中,当执行特定的操作后,编译器会智能地调整变量的类型范畴,这被称为控制流类型收窄。以下是一些常见的控制流类型收窄状况:

if 语句的条件判断

function printValue(value: string | number) {if (typeof value === 'string') {console.log(value.toUpperCase());
  } else {console.log(value.toFixed(2));
  }
}

在下面的示例中,当执行 typeof value === 'string' 的条件判断时,TypeScript 编译器会收窄 value 的类型为 string,从而在代码块外部提供相应的智能提醒和类型查看。

switch 语句的 case 判断

type Fruit = 'apple' | 'banana' | 'orange';

function getFruitColor(fruit: Fruit) {
  let color: string;
  switch (fruit) {
    case 'apple':
      color = 'red';
      break;
    case 'banana':
      color = 'yellow';
      break;
    default:
      color = 'orange';
  }
  console.log(`The color of ${fruit} is ${color}`);
}

在下面的示例中,依据 switch 语句中的 case 判断,TypeScript 编译器会智能地收窄 color 的类型为相应的色彩字符串。

真值类型守卫

真值收窄是一种在条件表达式中进行类型收窄的机制。当条件表达式的后果是真值时,TypeScript 编译

器会将变量的类型范畴放大为 true 的类型。以下是一个示例:

function processValue(value: string | null) {if (value) {console.log(value.toUpperCase());
  } else {console.log('Value is null or empty');
  }
}

在下面的示例中,当条件表达式 value 的后果是真值(即不为 null 或空字符串)时,TypeScript 编译器会将 value 的类型范畴放大为 string

自定义类型判断式(Type Predicates)守卫

TypeScript 提供了自定义类型判断式的性能,它容许咱们定义本人的谓词函数来进行类型判断和类型收窄。以下是一个示例:

interface Bird {fly(): void;
}

interface Fish {swim(): void;
}

function isBird(animal: Bird | Fish): animal is Bird {return (animal as Bird).fly !== undefined;
}

function processAnimal(animal: Bird | Fish) {if (isBird(animal)) {animal.fly();
  } else {animal.swim();
  }
}

在下面的示例中,咱们定义了 isBird 谓词函数来判断参数 animal 是否属于 Bird 类型。在 processAnimal 函数中,通过应用自定义谓词函数 isBird,咱们可能依据 animal 的具体类型执行相应的代码逻辑,并在代码块外部收窄 animal 的类型范畴。

正文完
 0