否定的用户定义类型保护

Negative user-defined type guards

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

告诉 typescript 宠物类型是 Fish

有没有办法相反地说明输入参数不是鱼?

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

您可以使用 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
}

您可以使用相同的函数来做到这一点,但该函数只返回 false