目 录CONTENT

文章目录

TS(十一)类型守卫

Typescript(十一) 类型守卫

TypeScript 类型守卫(Type Guard)用于 在运行时检查类型,让编译器在特定代码块内收窄类型 。

类型守卫分成四种

  • typeof
  • instanceof
  • in
  • is (自定义)

typeof 类型守卫

适用于基本类型: string 、 number 、 boolean 、 symbol 、 bigint 、 undefined 、 function

function process(value: string | number) {
  if (typeof value === "string") {
    value.toUpperCase(); // ✅ TS 知道这里是 string
  } else {
    value.toFixed(2); // ✅ TS 知道这里是 number
  }
}

instanceof 类型守卫

适用于类实例

class Dog {
  bark() {
    console.log("汪汪");
  }
}

class Cat {
  meow() {
    console.log("喵喵");
  }
}

function makeSound(animal: Dog | Cat) {
  if (animal instanceof Dog) {
    animal.bark(); // ✅ 收窄为 Dog
  } else {
    animal.meow(); // ✅ 收窄为 Cat
  }
}

in 类型守卫

检查对象是否有某个属性

interface Bird {
  fly: () => void;
}

interface Fish {
  swim: () => void;
}

function move(animal: Bird | Fish) {
  if ("fly" in animal) {
    animal.fly(); // ✅ 收窄为 Bird
  } else {
    animal.swim(); // ✅ 收窄为 Fish
  }
}

自定义类型守卫(最强大)

  • 使用is关键字,返回布尔值
interface User {
  name: string;
  email: string;
}

interface Admin {
  name: string;
  permissions: string[];
}

// 自定义类型守卫函数
function isAdmin(user: User | Admin): user is Admin {
  return "permissions" in user;
}

function getInfo(user: User | Admin) {
  if (isAdmin(user)) {
    console.log(user.permissions); // ✅ 收窄为 Admin
  } else {
    console.log(user.email); // ✅ 收窄为 User
  }
}

实际应用场景

处理unknown类型

function isString(value: unknown): value is string {
  return typeof value === "string";
}

function isNumber(value: unknown): value is number {
  return typeof value === "number";
}

function processData(data: unknown) {
  if (isString(data)) {
    return data.trim();
  }
  if (isNumber(data)) {
    return data.toFixed(2);
  }
  return null;
}

数组过滤

function isDefined<T>(value: T | undefined | null): value is T {
  return value !== undefined && value !== null;
}

const items = [1, undefined, 2, null, 3];
const validItems = items.filter(isDefined); // number[],不是 (number | null | undefined)[]

// 不用类型守卫会这样:
// const bad = items.filter(x => x !== undefined);  // 还是 (number | null | undefined)[]

核心要点

守卫方式 适用场景 语法
typeof 基本类型 typeof value === "string"
instanceof 类实例 instanceof Dog
in 检查属性 "fly" in animal
is 自定义类型 x is Type
0
博主关闭了当前页面的评论