「TypeScript」类型守卫(TypeGuard)🍃

一、简介

 TypeScript中的类型守卫(Type Guards)是一种技术,它可以用于在代码中更明确地指定变量的类型。这是TypeScript提供的一种强大功能,因为它可以帮助开发者避免类型错误,同时还能利用TypeScript的类型系统来提供更好的代码智能提示和自动补全。类型守卫主要用于告诉TypeScript编译器,某个变量在特定的代码块中是特定的类型。

二、使用场景

 类型守卫一般要配合if语句,在if语句创建的块级作用域中收窄对应变量的类型。当然也可以使用三目运算符、逻辑与运算符等使用。

1. 区分联合类型

typescript 复制代码
function process(input: string | number) {
  if (typeof input === "string") {
    // do something...
  } else {
    // do something...
  }
}

2. 收窄类型

typescript 复制代码
function move(animal: Animal) {
  if (animal instanceof Bird) {
    animal.fly();
  } else if (animal instanceof Fish) {
    animal.swim();
  } else {
    // do something...
  }
}

3. 处理未知类型

typescript 复制代码
function move(animal: unknown) {
  // do something...
}

三、写法

1. "instanceof " 操作符

 当你想要检查一个对象是否是某个类的实例时,可以使用instanceof

typescript 复制代码
abstract class Animal {
  abstract makeSound(): void;
}

abstract class Fish extends Animal {
  abstract swim(): void;
}

abstract class Bird extends Animal {
  abstract fly(): void;
}

class Shark extends Fish {
  makeSound() {
    console.log("Shark make sound");
  }

  swim() {
    console.log("Shark swim");
  }
}

class Eagle extends Bird {
  makeSound() {
    console.log("Eagle make sound");
  }

  fly() {
    console.log("Eagle fly");
  }
}

function getMovement(animal: Animal) {
  if (animal instanceof Fish) {
    // 在这个作用域(if创建的作用域)中,animal 被收窄为 Fish
    return animal.swim();
  }

  if (animal instanceof Bird) {
    // 在这个作用域(if创建的作用域)中,animal 被收窄为 Bird
    return animal.fly();
  }
}

2. "in" 操作符

 这种方式主要用于检查一个具有特定属性的对象。

typescript 复制代码
abstract class Animal {
  abstract makeSound(): void;
}

abstract class Fish extends Animal {
  abstract swim(): void;
}

abstract class Bird extends Animal {
  abstract fly(): void;
}

class Shark extends Fish {
  makeSound() {
    console.log("Shark make sound");
  }

  swim() {
    console.log("Shark swim");
  }
}

class Eagle extends Bird {
  makeSound() {
    console.log("Eagle make sound");
  }

  fly() {
    console.log("Eagle fly");
  }
}

function getMovement2(animal: Animal) {
  if ("swim" in animal) {
    return animal.swim();
  }

  if ("fly" in animal) {
    return animal.fly();
  }
}

3. 自定义类型守卫

 在复杂的应用中,可能需要基于特定逻辑来确定变量的类型,此时可以创建自定义的类型守卫。通过类型谓词"is" 实现变量类型的收窄。

typescript 复制代码
abstract class Animal {
  abstract makeSound(): void;
}

abstract class Fish extends Animal {
  abstract swim(): void;
}

abstract class Bird extends Animal {
  abstract fly(): void;
}

class Shark extends Fish {
  makeSound() {
    console.log("Shark make sound");
  }

  swim() {
    console.log("Shark swim");
  }
}

class Eagle extends Bird {
  makeSound() {
    console.log("Eagle make sound");
  }

  fly() {
    console.log("Eagle fly");
  }
}

function isAccurateAnimal<T extends Animal>(
  animal: unknown,
  type: abstract new (...args: any[]) => T
): animal is T {
  return animal instanceof type;
}

function getMovement(animal: Animal) {
  if (isAccurateAnimal(animal, Fish)) {
    animal.swim();
  }

  if (isAccurateAnimal(animal, Bird)) {
    animal.fly();
  }
}

 自定义类型守卫传入需要收窄类型的变量,并定义相应的收窄类型,返回布尔值的结果,当结果为真则变量的类型收窄为定义的类型,反之不进行收窄。

typescript 复制代码
function narrowType(object: unknown): object is [NarrowedType] {
  return [condition]
}
相关推荐
退休倒计时1 天前
【每日一题】LeetCode 146. LRU 缓存 TypeScript
算法·leetcode·缓存·typescript
kyriewen2 天前
TypeScript 高级类型:我用 infer 写了一个类型安全的 EventBus,终于搞懂了泛型约束
前端·javascript·typescript
月光刺眼2 天前
Bun + TypeScript 后端入门:从类型约束到 LLM API 调用
后端·typescript
天蓝色的鱼鱼2 天前
Node.js 现在能直接跑 TypeScript 了,tsx 和 ts-node 还需要吗?
前端·typescript·node.js
Oo9202 天前
Bun:下一代 JavaScript/TypeScript 运行时,从入门到实践
typescript·bun
Asize3 天前
Bun + TypeScript 实战:从接口约束到 RESTful 路由设计
后端·typescript·代码规范
大家的林语冰3 天前
超越 TypeScript,Flow 强势回归,语法高仿 TS,功能更丰富,类型更安全!
前端·javascript·typescript
用户484526255823 天前
Bun 入门:Bun.serve 零依赖启动 HTTP 服务
typescript
meilindehuzi_a4 天前
构建基于 RESTful 架构的 TodoList 全栈应用:从前后端理论到 TypeScript/Bun 实战
架构·typescript·restful
云水一下4 天前
Vue.js从零到精通系列(七):高级特性实战——Teleport、异步组件、自定义指令与TypeScript深度结合
前端·vue.js·typescript