负的用户定义类型保护

tru*_*ru7 6 typescript type-narrowing

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

告诉打字稿宠物类型是 Fish

有没有办法相反,输入参数不是鱼?

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

Tit*_*mir 8

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

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

或者更通用的版本:

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
}
Run Code Online (Sandbox Code Playgroud)