什么是类型守卫(Type Guard)?typeof / instanceof / in / 自定义守卫怎么用?
类型守卫是运行时检查 + 编译期收窄的手段:
// 1) typeof:基本类型
function f(x: string | number) { if (typeof x === 'string') x.trim() }
// 2) instanceof:类实例
if (err instanceof TypeError) err.message
// 3) in:对象属性存在
if ('swim' in animal) animal.swim()
// 4) 自定义守卫:用 is 断言
function isFish(p: Fish | Bird): p is Fish {
return (p as Fish).swim !== undefined
}
if (isFish(pet)) pet.swim() // 此处 pet 收窄为 Fishp is Fish 告诉编译器:若返回 true,则参数就是 Fish,从而安全调用其特有方法。