X | undefined 在不检查箭头函数的情况下缩小到从不



启用strictNullChecks时,以下代码会在 TypeScript 中产生错误:

function foo(cb) {
cb()
}
let h: { a: number } | undefined = undefined // required to reproduce this bug
foo(() => h = { a: 1 })
if (h) {
console.log(h.a) // <-- h is of type `never`
}

打字稿游乐场

这是 TypeScript 控制流分析的设计限制。

引用:

https://github.com/Microsoft/TypeScript/issues/28038

https://github.com/Microsoft/TypeScript/issues/9998

最新更新