Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative user-defined type guards

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;
}
like image 672
tru7 Avatar asked Jun 16 '18 20:06

tru7


People also ask

What is a type guard in TypeScript?

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.

What is TypeGuard in Python?

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.

What is a type predicate?

A type predicate is a specially-defined function that returns a boolean when a specified argument returns true.


1 Answers

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
}
like image 132
Titian Cernicova-Dragomir Avatar answered Sep 28 '22 19:09

Titian Cernicova-Dragomir