【发布时间】:2016-07-14 23:58:33
【问题描述】:
假设我有这样的代码:
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 在console.log 处具有类型string。但是当从.then 中的闭包中引用时,它的类型是string | undefined。这一定是因为在.then 中的代码运行之前,值可能会在类型保护之外变回未定义。但是,如果它没有再次设置,Typescript 肯定不会进行可以让它检测到的那种分析。
我可以通过在x 上使用! 运算符来解决它。但是我发现我经常在我的代码库中做这种事情,并且它并不能防止以后通过使 x 未定义而被破坏。
还有其他方法可以解决这个问题吗?我是否正确理解了这个问题?
【问题讨论】:
标签: typescript closures typescript2.0