假设我有这样的代码:
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 一定不会进行那种让它检测到的分析。
我可以使用 !
来解决这个问题运算符 x
。但我发现我经常在我的代码库中做这种事情,并且它不能防止以后因使 x 未定义而被破坏。
还有其他办法解决这个问题吗?我对问题的理解正确吗?
最佳答案
我认为您可以执行以下任一操作:
(1)使用const:
function f(x: string | undefined) {
if (x) {
const x2 = x;
Promise.resolve().then(() => g(x2));
} else {
// x = undefined;
}
}
(2) 在promise之前调用g()
:
function f(x: string | undefined) {
if (x) {
let y = g(x);
Promise.resolve().then(() => y);
} else {
// x = undefined;
}
}
关于Typescript strictNull 检查和闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38378652/