假设我有这样的代码:
function f(x: string | undefined) {
if (x) {
console.log(x);
Promise.resolve()
.then(() => g(x)) // error, x is string | undefined
}
// x = undefined;
}
function g(y: string) {
}
if (x)
充当类型保护x
,因此string
在console.log
. 但是当从 中的闭包中引用时.then
,它的类型是string | undefined
. .then
这一定是因为在代码运行之前,该值可能会在类型保护之外更改回未定义。但是,如果它没有再次设置,Typescript 一定不会进行那种可以让它检测到的分析。
!
我可以通过使用运算符 on来解决它x
。但是我发现我经常在我的代码库中做这种事情,并且它并不能防止以后通过使 x 未定义而被破坏。
有没有其他方法可以解决这个问题?我是否正确理解了这个问题?