Typescript “错误”;操作员'==';无法应用于类型';假';和';正确'&引用;错误?

Typescript “错误”;操作员'==';无法应用于类型';假';和';正确'&引用;错误?,typescript,Typescript,为什么不允许检查属性的更改值 public static enumerateDescendants(ancestor: Node, cb: (node: Node, settings: { stopContinueVertical: boolean }) => any): void { const settings: { stopContinueVertical: boolean } = { stopContinueVertical: false }; MyCla

为什么不允许检查属性的更改值

public static enumerateDescendants(ancestor: Node,
    cb: (node: Node, settings: { stopContinueVertical: boolean }) => any): void {
    const settings: { stopContinueVertical: boolean } = { stopContinueVertical: false };

    MyClass.enumerateChildren(
        ancestor, (node) => {
            settings.stopContinueVertical = false;
            cb(node, settings);

            if (settings.stopContinueVertical as any !== true) /*!! Here as any is required*/{
                MyClass.enumerateDescendants(node, cb);
            }
        }
    );
}

public static doWork(): void {
    MyClass.enumerateDescendants(
        MyClass.getCurrentNode(), (node, settings) => {
            /*Do some work*/
            settings.stopContinueVertical = true; /*!! Here the value is changed*/
        }
    );
}

如果我没有像任何人一样使用
,我会得到
(TS)操作符'!='无法应用于类型“false”和“true”。

以下是错误的详细信息:

[ts]此条件将始终返回'true',因为'false'和'true'类型没有重叠。 (属性)stopContinueVertical:false

因此,由于它在上面被设置为常量
false
,所以它知道如果
是完全冗余的,因此会抛出一个错误。

主要问题是:当调用函数时,我们应该假设它的副作用是什么

一种选择是悲观并重置所有狭窄,假设任何函数都可能变异它可能得到的任何对象。另一种选择是乐观,并假设函数不修改任何状态。这两个似乎都不好

当前的实现更倾向于后一个选项,这就是导致问题的原因-编译器无法跟踪
MyClass.EnumeratedSubjects
发生变异
设置
,因此它认为您正在对一个永远不变的值执行比较


不幸的是,除了你已经尝试过的解决方法之外,没有其他方法可以解决这个问题。TypeScript回购协议的相关问题是——这是一个有趣的阅读。

可能重复@misorude,可能不是,在另一篇文章中有一个编程错误。在这篇文章中,stopContinueVertical实际上可以更改。它不是常量
const设置:{stopContinueVertical:boolean}={stopContinueVertical:false}指定给常量变量的对象并不会神奇地使其所有属性都常量化,因为您是对的。显然,typescript预测它不会在其他任何地方更改,即使它可以通过回调
cb
进行修改。很明显,你在TypeScript中发现了一个bug-请转到并报告问题OK谢谢,在提交问题之前,我会先尝试更新到3.1.1。也许已经修好了。