TypeScript类型守卫:让代码更安全的小技巧(实战经验分享)

什么是型守卫

在写前端项目时,经常会遇到一个函数接收多种类型的参数。比如某个变量可能是字符串,也可能是数字,甚至是一个对象。这时候如果不做判断,直接调用方法很容易出错。TypeScript 的类型守卫就是用来解决这个问题的工具,它能让你在运行时准确判断变量的具体类型,从而安全地进行操作。

常见的类型守卫方式

最简单的类型守卫是使用 typeof 检查基础类型。比如你有一个函数处理数字或字符串:

function formatValue(value: string | number): string {
  if (typeof value === 'string') {
    return value.trim().toUpperCase();
  }
  return value.toFixed(2);
}

这里 TypeScript 能识别 typeof value === 'string' 这个条件,自动将 value 在该分支中视为字符串类型,避免调用 toFixed 出错。

使用 instanceof 判断对象类型

当你处理的是 Date、Error 或自定义类实例时,instanceof 就派上用场了。例如:

function handleError(err: Error | string): void {
  if (err instanceof Error) {
    console.error('错误详情:', err.message);
  } else {
    console.error('原始信息:', err);
  }
}

在这个例子中,TypeScript 知道进入第一个分支后 err 就一定是 Error 类型,可以放心访问其属性。

自定义类型守卫函数

有时候类型判断逻辑比较复杂,比如要区分一个对象是不是某个接口的实现。这时候可以写一个返回类型谓词的函数:

interface Dog {
  bark(): void;
}

interface Cat {
  meow(): void;
}

function isDog(animal: Dog | Cat): animal is Dog {
  return (animal as Dog).bark !== undefined;
}

function makeSound(animal: Dog | Cat) {
  if (isDog(animal)) {
    animal.bark(); // TypeScript 确认这是 Dog
  } else {
    animal.meow(); // 自动推断为 Cat
  }
}

注意函数返回值写法 animal is Dog,这告诉编译器这个函数的返回值为 true 时,参数 animal 就属于 Dog 类型。

在实际项目中的好处

比如你在做一个表单校验功能,输入数据来自用户,类型不确定。通过类型守卫提前判断,不仅能防止运行时报错,还能让后续逻辑更清晰。团队协作时,别人看你的代码也能立刻明白每种情况的处理依据,减少沟通成本。类型守卫就像给代码加了一道安检门,确保每一步都走得踏实。