【发布时间】:2018-11-30 15:03:57
【问题描述】:
我遇到了一个问题,即 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.
}
已经提出了一些 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 版
【问题讨论】:
-
解决方法:使用
let result = _.some(p, s => s === 'Two');:) -
你可以使用
for... of -
@HereticMonkey 是的,那肯定会更干净。而且更优雅。但是,我更多地使用该示例进行演示,而不是实际使用。
标签: typescript