类型判断式
type predicates

Preview

Preview
等价于

Preview
在这个例子中,pet is Fish
就是我们的类型判断式,一个类型判断式采用 parameterName is Type
的形式, parameterName
必须是当前函数的参数名,意思是如果函数返回 true
,那么参数 parameterName
类型就是 type
。
类型判断式是类型收窄的一种形式,其他形式还有 typeof 收窄、in 操作符收窄、instanceof 收窄、真值收窄等。
什么是类型收窄

Preview
上面例子中,参数 str
的初始类型是由 string
、string[]
、null
组成的联合类型,经过“操作”后,类型变得更具体、确切。