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

何时需要“is”谓词,而不是使用“in”运算符?

  •  1
  • dwjohnston  · 技术社区  · 5 年前

    According to the TypeScript documentation

    文档给出了使用 is in 接线员。

    谓语:

    function isFish(pet: Fish | Bird): pet is Fish {
        return (pet as Fish).swim !== undefined;
    }
    
    if (isFish(pet)) {
        pet.swim();
    }
    else {
        pet.fly();
    }
    

    在里面 操作员:

    function move(pet: Fish | Bird) {
        if ("swim" in pet) {
            return pet.swim();
        }
        return pet.fly();
    }
    

    在里面

    有什么情况 谓词可以区分 接线员不能?

    1 回复  |  直到 5 年前
        1
  •  1
  •   kaya3 Amit Bera    5 年前

    这个 in 运算符只是缩小变量类型的一种方法。你可以用任何你喜欢的支票写类型保护:

    type JSONPrimitive = number | string | boolean | null;
    
    function isJsonPrimitive(x: any): x is JSONPrimitive {
        return x === null
            || typeof x === 'number'
            || typeof x === 'string'
            || typeof x === 'boolean';
    }
    

    interface TreeNode {
        value: number;
        left: TreeNode | null;
        right: TreeNode | null;
    }
    type InternalNode = TreeNode & ({ left: TreeNode } | { right: TreeNode });
    
    function isInternalNode(node: TreeNode): node is InternalNode {
        return node.left !== null || node.right !== null;
    }
    

    使用 在里面

    也就是说,用户定义的类型保护类似于 type assertions ,在该类型脚本中不检查它们的正确性。因此,您可以在类型保护的实现中使用任何您喜欢的逻辑;甚至是无条件的 return true;