Negative user-defined type guards
Asked Answered
R

2

15
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;
}
Rictus answered 16/6, 2018 at 20:37 Comment(0)
M
20

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
}
Mistreat answered 16/6, 2018 at 20:50 Comment(0)
L
0

You can do that by using the same function, but the function just retuns false.

Limbourg answered 16/6, 2018 at 20:50 Comment(1)
Do you mind sharing an example? Wouldn't that still return a Fish type when the thing is not a fish?Jaysonjaywalk

© 2022 - 2024 — McMap. All rights reserved.