function isFish(pet: Fish | Bird): pet is Fish {
return (<Fish>pet).swim !== undefined;
}
tells typescript that pet type is Fish
Is there a way to state the contrary, that the input parameter is NOT a Fish?
function isNotFish(pet: Fish | Bird): pet is not Fish { // ????
return pet.swim === undefined;
}
A type guard is a TypeScript technique used to get information about the type of a variable, usually within a conditional block. Type guards are regular functions that return a boolean, taking a type and telling TypeScript if it can be narrowed down to something more specific.
TypeGuard is a special form that accepts a single type argument. It is used to annotate the return type of a user-defined type guard function. Return statements within a type guard function should return bool values, and type checkers should verify that all return paths return a bool.
A type predicate is a specially-defined function that returns a boolean when a specified argument returns true.
You can use the Exclude
conditional type to exclude types from a union :
function isNotFish(pet: Fish | Bird): pet is Exclude<typeof pet, Fish>
{
return pet.swim === undefined;
}
Or a more generic version :
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With