打字稿编译器错误地假设为假值

时间:2018-11-30 15:03:58

标签: typescript

我遇到一个问题,打字稿编译器假设变量始终为false,因为这就是声明的方式。

代码非常简单,要引入错误,我必须使用外部库来修改声明的变量。在这种情况下,我正在使用lodash。

import * as _ from 'lodash'; // as an example

let p = ["One", "Two"];
let result = false;

_.each(p, s => {
    if (s === "Two") {
        result = true;
        return;
    }
});

if (result === true) { // Compiler error - this condition will always return false
    // do something.
}

Playground Link

提出了一些github问题:

https://github.com/Microsoft/TypeScript/issues/27910

https://github.com/Microsoft/TypeScript/issues/27401

https://github.com/Microsoft/TypeScript/issues/9998

所有这些似乎都比上面的简单可复制的要复杂一些。这是TypeScript的预期行为吗?看来这里还不够。我很确定在版本2中不会发生这种情况。

有解决方法吗?我在做错什么吗?

当前我正在使用TypeScript版本3.2.1

1 个答案:

答案 0 :(得分:1)

将代码更改为此:

let result = false as boolean;

打字稿抱怨的原因是它认为它比实际要聪明,即看到您为false变量分配了result值,但却没有看到< / em>回调函数中的操作。

我真的不知道为什么Typescript团队会这样做。他们肯定有其原因,但他们也从您的示例中漏掉了这个案例。

由于回调,TS可能认为操作_.each是异步的,但是当然,并非每个涉及回调的操作都是异步的。