gpt4 book ai didi

typescript - 否定的用户定义类型保护

转载 作者:搜寻专家 更新时间:2023-10-30 21:04:25 25 4
gpt4 key购买 nike

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
}

关于typescript - 否定的用户定义类型保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50891567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com