带你读《现代TypeScript高级教程》十、类型守卫(1)

简介: 带你读《现代TypeScript高级教程》十、类型守卫(1)

十、类型守卫

1. 概述

在 TypeScript 中,类型守卫可以用于在运行时检查变量的类型,并在代码块内部将变量的类型范围缩小到更具体的类型。这种类型收窄可以让 TypeScript 编译器更好地理解我们代码的意图,从而提供更准确的类型推断和类型检查。

 

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

2. typeof 类型守卫

typeof 类型守卫允许我们使用 typeof 操作符来在代码中根据变量的类型范围进行条件判断。以下是一个示例:

 

function printValue(value: string | number) {
  if (typeof value === 'string') {
    console.log(value.toUpperCase());
  } else {
    console.log(value.toFixed(2));
  }}
printValue('hello');  // 输出: HELLOprintValue(3.1415);   // 输出: 3.14

 

在上面的示例中,我们使用 typeof 操作符在条件语句中检查变量 value 的类型。如果它的类型是 'string',则调用 toUpperCase 方法;如果是 'number',则调用 toFixed 方法。通过使用 typeof 类型守卫,我们能够根据不同的类型执行不同的代码逻辑。

  1. 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 movingperformAction(animal2);  // 输出: Dog is barking

 

在上面的示例中,我们使用 instanceof 操作符在条件语句中检查变量 animal 的类型。如果它是 Dog 类的实例,则调用 bark 方法;否则调用 move 方法。通过使用 instanceof 类型守卫,我们可以根据对象的具体类型执行不同的代码逻辑。

  1. 使用自定义谓词函数类型守卫

自定义谓词函数类型守卫允许我们定义自己的函数,根据特定条件判断变量的类型,并在代码块内部收窄变量的类型范围。以下是一个示例:

 

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.53981633974483calculateArea(rectangle);  // 输出: 200

 

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


带你读《现代TypeScript高级教程》十、类型守卫(2)https://developer.aliyun.com/article/1348510?groupCode=tech_library

相关文章
|
2天前
|
JavaScript 前端开发
37.【TypeScript 教程】TSLint 与 ESLint
37.【TypeScript 教程】TSLint 与 ESLint
5 0
|
2天前
|
JavaScript 编译器 IDE
36.【TypeScript 教程】tsconfig.json 配置
36.【TypeScript 教程】tsconfig.json 配置
5 0
|
2天前
|
JavaScript 编译器
35.【TypeScript 教程】编译选项
35.【TypeScript 教程】编译选项
5 2
|
2天前
|
JavaScript 前端开发 编译器
34.【TypeScript 教程】声明合并
34.【TypeScript 教程】声明合并
7 0
|
2天前
|
JavaScript 编译器
33.【TypeScript 教程】命名空间
33.【TypeScript 教程】命名空间
10 2
|
2天前
|
JavaScript 编译器 开发者
32.【TypeScript 教程】模块
32.【TypeScript 教程】模块
6 0
|
2天前
|
JavaScript 编译器
31.【TypeScript 教程】混入(Mixins)
31.【TypeScript 教程】混入(Mixins)
12 3
|
2天前
|
JavaScript Java API
30.【TypeScript 教程】Reflect Metadata
30.【TypeScript 教程】Reflect Metadata
10 4
|
2天前
|
JavaScript 监控 编译器
29.【TypeScript 教程】装饰器(Decorator)
29.【TypeScript 教程】装饰器(Decorator)
6 0
|
2天前
|
JavaScript
28.【TypeScript 教程】生成器(Generator)
28.【TypeScript 教程】生成器(Generator)
9 3