1

假设我有这样的代码:

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 一定不会进行那种可以让它检测到的分析。

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

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

4

1 回答 1

3

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

(1) 使用常量:

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

g()(2)在promise之前调用:

function f(x: string | undefined) {
    if (x) {
        let y = g(x);
        Promise.resolve().then(() => y);
    } else {
        // x = undefined;
    }
}
于 2016-07-14T15:58:33.190 回答