在了解类型谓词之前,我们先来了解联合类型。
联合类型
日常开发中,我们会定义为一个支持多种类型的变量,比如一个变量可以是 sting
或者 number
let page: string | number = 1;type Fish = { swim: () => void};type Bird = { fly: () => void}type Human = { swim?: () => void fly?: () => void}let animal: Fish | Bird | Human = ...;
类型保护
官方文档的描述
A type guard is some expression that performs a runtime check that guarantees the type in some scope.
类型保护主要的想法是尝试检测属性、方法或原型,以弄清楚如何处理一个值。有四种使用类型保护的主要方法,分别是 in
,typeof
,instanceof
,类型谓词
类型谓词
类型谓词是一种特殊的返回类型,它向 Typescript 编译器发出一个特定值是什么类型的信号。类型谓词总是附加到接受单个参数并返回布尔值的函数。类型谓词表示为 argumentName is Type
function isFish(pet: Fish | Bird): pet is Fish { return (pet as Fish).swim !== undefined;}
这里的 pet is Fish
就是类型谓词,pet
必须是函数的参数
当 isFinis()
调用并且返回 true 的时候,ts 就会把该变量的类型范围缩小为某一具体类型
let pet = getSmallPet();if (isFish(pet)) { // isFinish为true,那么pet就是Fish pet.swim();} else { pet.fly();}