Typescript strictNull 检查和闭包

标签 typescript closures typescript2.0

假设我有这样的代码:

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类型为stringconsole.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/

相关文章:

javascript - typescript : add prototype method for a object which implements and interface or extend DTO

html - 更改选项中文本的颜色

typescript - 如何使用 Webpack 和 Angular2 包含外部 css 文件?

javascript - 如何使 CoffeeScript 闭包感知非局部变量?

php - 有没有办法在 PHP 匿名函数中不捕获 $this?

javascript - 在循环内定义函数,i 的值未定义或不可预测

javascript - 仅将第一个返回值打印到 Angular2 App 中的 View

javascript - 如何一次性获取BehaviorSubject的当前值?

typescript - Firebase Cloud Functions Firestore 触发器产生 : Error: 7 PERMISSION_DENIED: Missing or insufficient permissions

javascript - typescript + 终极版 : exclude redux props in parent component