在缩小联合类型范围时,我总是被“in”的使用绊倒。我一直问自己为什么我们不能只检查属性以缩小范围?
示例...
type Obj1 = {
message: string
}
type Obj2 = {
text: string
}
const getText = (obj: Obj1 | Obj2): string => {
if (obj.message) { // <- 'message' does not exist on type 'Obj1 | Obj2'
return obj.message
}
return obj.text
}
相反,我们必须写:
const getText2 = (obj: Obj1 | Obj2): string => {
if ("message" in obj) {
return obj.message
}
return obj.text
}
为什么?
在
if (obj.message)
的情况下,还有一个基于真实性的布尔强制转换步骤。 if 条件需要布尔表达式,而 obj.message
返回 string
,因此 string
必须转换为 boolean
。
相反,运算符
in
、instanceof
和 typeof
不需要额外的布尔强制步骤。
这两个链接是我找到信息的地方:
https://www.typescriptlang.org/docs/handbook/2/narrowing.html#truthiness-narrowing https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-in-operator-narrowing