负面的用户定义类型保护

时间:2018-06-16 20:37:43

标签: typescript type-narrowing

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

告诉打字稿,宠物类型为Fish

有没有办法说明相反的情况,输入参数不是Fish?

function isNotFish(pet: Fish | Bird): pet is not Fish {  // ????
       return pet.swim === undefined;
}

2 个答案:

答案 0 :(得分:4)

您可以使用Exclude条件类型从联合中排除类型:

function isNotFish(pet: Fish | Bird): pet is Exclude<typeof pet, Fish>    
{ 
    return pet.swim === undefined;
}

或更通用的版本:

function isNotFishG<T>(pet: T ): pet is Exclude<typeof pet, Fish>    { 
    return pet.swim === undefined;
}
interface Fish { swim: boolean }
interface Bird { crow: boolean }
let p: Fish | Bird;
if (isNotFishG(p)) {
    p.crow
}

答案 1 :(得分:2)

你可以使用相同的功能,但该功能只返回false