Typescript strictNullChecks和closures

时间:2016-07-14 15:44:04

标签: 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)充当了类型保护,因此xstring处有console.log类型。但是当从.then中的闭包引用时,其类型为string | undefined。这必须是因为在.then中的代码运行之前,值可能会在类型保护之外变回未定义。但如果它没有再次设置,那么Typescript就不能进行那种让它检测到它的分析。

我可以使用!上的x运算符解决此问题。但是我发现我经常在我的代码库中执行此类操作,并且它不能防止以后通过使x未定义而被破坏。

还有其他方法吗?我能正确理解这个问题吗?

1 个答案:

答案 0 :(得分:3)

我认为你可以做其中任何一个:

(1)使用const:

function f(x: string | undefined) {
    if (x) {
        const x2 = x;
        Promise.resolve().then(() => g(x2));
    } else {
        // x = undefined;
    }
}

(2)在承诺之前致电g()

function f(x: string | undefined) {
    if (x) {
        let y = g(x);
        Promise.resolve().then(() => y);
    } else {
        // x = undefined;
    }
}