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

问题描述 投票:1回答:1

According to the TypeScript documentation,我们可以使用TypeGuard区分类型。

文档提供了使用is谓词和in运算符的示例。

is谓词:

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

if (isFish(pet)) {
    pet.swim();
}
else {
    pet.fly();
}

[in运算子:

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

in运算符似乎更加简洁和简单-尽管从长远来看,也许将类型区分显式地拉入函数是有用的,并且更易于维护。

[在任何情况下is谓词都可以区分in运算符无法区分的类型吗?

typescript
1个回答
0
投票

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;
}

这些示例均不能使用in运算符等效地重写。

也就是说,用户定义的类型保护类似于type assertions,因为Typescript不会检查其正确性。因此,您可以在实现类型保护时使用任何喜欢的逻辑。甚至允许无条件的return true;

© www.soinside.com 2019 - 2024. All rights reserved.