使用 Typescript 3.7空值合并运算符被介绍了。对于像这样的情况,它似乎是完美的类型保护
const fs = (s: string) => s
const fn = (n: number) => n
let a: string | null | undefined
let b: number | null | undefined
const x = (a ?? null) && fs(a)
const y = (b ?? null) && fn(b)
但是如果你将该代码放入打字稿游乐场,它会提醒您传递给 fs / fn 函数的 a 和 b 参数,例如:
I experimented a bit further and found it is not only an issue isolated to the nullish coalescing operator, but couldn't bend my mind around when typescript is able to use soemthing as a typeguard and when not (below you find some examples)
最后两行最让我困惑。在我看来,分配给 x7 和 x8 的两个表达式是完全等效的,但是在分配给 x8 的表达式中,类型保护起作用,但对于 x7 表达式中的 typescript 来说似乎不行:
const fs = (str: string) => str
const create = (s: string) => s === 's' ? 'string' : s === 'n' ? null : undefined
const a: string | null | undefined = create('s')
const b: string | null | undefined = 's'
let x
if (a !== null && a !== undefined) {
x = a
} else {
x = fs(a)
}
const x1 = a !== null && a !== undefined && fs(a)
const x2 = a !== null && a !== void 0 && fs(a)
const x3 = (a ?? null) && fs(a)
const x4 = (b ?? null) && fs(b)
const x5 = a !== null && a !== undefined ? a : fs(a)
const something = a !== null && a !== undefined
const x6 = something ? a : fs(a)
const x7 = something && fs(a)
const x8 = (a !== null && a !== undefined) && fs(a)
我不确定打字稿是否由于某种原因无法应用类型保护,或者它实际上是打字稿中的一个错误。那么是否存在某种规则手册,什么时候 typescript 可以应用 typeguard,什么时候不可以呢?或者这可能是一个错误?或者还有其他原因导致我无法编译这些示例吗?
顺便提一句。当使用用户定义的类型保护时,当然可以完美地工作,但最好不必为类型保护添加一些运行时代码来工作。