HomeToolsAbout

Type Predicate

What is it

is checks if a value is of a specified type and returns a boolean output

// below narrows to string function isString(test: any): test is string{ return typeof test === "string"; }

Syntax of variableName is variableType

// `pet is Fish` function isFish(pet: Fish | Bird): pet is Fish { // returns boolean return (pet as Fish).swim !== undefined; } let pet: Fish | Bird; if(isFish(pet)) { // true, pet is Fish pet.swim(); } else { // false, pet is NOT Fish pet.fly(); }

Any time isFish is called with some variable, TypeScript will narrow that variable to that specific type if the original type is compatible

// Both calls to 'swim' and 'fly' are now okay let pet = getSmallPet(); if (isFish(pet)) { pet.swim(); } else { pet.fly(); }

Notice that TypeScript not only knows that pet is a Fish in the if branch; it also knows that in the else branch, you don’t have a Fish, so you must have a Bird.

You may use the type guard isFish to filter an array of Fish | Bird and obtain an array of Fish

Predicate over Boolean

Difference between using Boolean as a return type and type predicate is that when using a type predicate, the boolean return value of type predicate will be understood by TS as narrowing of type

// this type predicate function will return a boolean function isString(test: any): test is string{ return typeof test === "string"; } function example(foo: any){ // `isString` return value is not just a boolean, but understood as a `String` type enforcement if(isString(foo)){ console.log("it is a string" + foo); console.log(foo.length); // string function is guaranteed to run as expected } }
AboutContact