【问题标题】:Typescript strictNullChecks and closuresTypescript strictNullChecks 和闭包
【发布时间】: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) 充当类型保护,因此xconsole.log 处具有类型string。但是当从.then 中的闭包中引用时,它的类型是string | undefined。这一定是因为在.then 中的代码运行之前,值可能会在类型保护之外变回未定义。但是,如果它没有再次设置,Typescript 肯定不会进行可以让它检测到的那种分析。

我可以通过在x 上使用! 运算符来解决它。但是我发现我经常在我的代码库中做这种事情,并且它并不能防止以后通过使 x 未定义而被破坏。

还有其他方法可以解决这个问题吗?我是否正确理解了这个问题?

【问题讨论】:

    标签: typescript closures typescript2.0


    【解决方案1】:

    我认为您可以执行以下任一操作:

    (1) 使用常量:

    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;
        }
    }
    

    【讨论】:

    • 1 - 好点子,事实上并不是你有一个 const 引用,而是你有一个新的引用,它只是类型为string。所以letvar 也可以。虽然会导致一些混乱。 2 - 是的,但在我想到的场景中,我通常无法做到这一点。否则我已经会了:)
    • 是的,我想你对 const 部分是正确的,我开始尝试将它放在函数的参数中,但这是不允许的,所以我将它复制到函数的主体而不将其更改为var/let.
    猜你喜欢
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 2017-02-15
    相关资源
    最近更新 更多