Typescript strictNullChecks 和闭包

Typescript strictNullChecks and closures

假设我有这样的代码:

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 未定义而被破坏。

还有其他解决办法吗?我对问题的理解是否正确?

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

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