代码之家  ›  专栏  ›  技术社区  ›  user764754

错误的“运算符”!=='不能应用于类型“false”和“true”。“错误?

  •  2
  • user764754  · 技术社区  · 6 年前

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

    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*/
            }
        );
    }
    

    如果我不使用 as any (TS) Operator '!==' cannot be applied to types 'false' and 'true'.

    2 回复  |  直到 6 年前
        1
  •  1
  •   Community CDub    5 年前

    To quote one of the TypeScript developers, on the topic of the compiler's control flow analysis:

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

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

    MyClass.enumerateDescendants 变异 settings

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

        2
  •  0
  •   CoderPi    6 年前

    enter image description here

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

    既然设置为常量 false 上面写着 if

    推荐文章