🧪 Frontend Lab
交互式前端学习实验室

类型守卫

typescript · intermediate · 15 min · Step 1/2

类型守卫

// 普通函数 — TS 不理解返回值含义
function isCat(pet: Pet): boolean {
  return 'meow' in pet;
}

// 类型守卫 — TS 理解 true 意味着是 Cat
function isCat(pet: Pet): pet is Cat {
  return 'meow' in pet;
}

// 使用
if (isCat(pet)) {
  pet.meow();  // TS 知道这里是 Cat
} else {
  pet.bark();  // TS 知道这里是 Dog
}

断言函数

function assertIsString(val: unknown): asserts val is string {
  if (typeof val !== 'string') throw new Error('Not a string!');
}

const x: unknown = 'hello';
assertIsString(x);
console.log(x.toUpperCase());  // TS 知道 x 是 string