How to use TypeScript Custom Predicate for Narrowing

In TypeScript, narrowing refers to refining the type of a variable within a specific block of code. It allows TypeScript to infer a more particular type from a broader type based on runtime checks or control flow.

Narrowing is used for better type safety, ensuring that only properties or methods on a type can be accessed. It prevents runtime errors caused by accessing invalid properties or methods.

In TypeScript, you can use a Custom Predicate for narrowing.  Let us see how we can do that.

Let us say you have two types,

type Fish = { swim: () => void };
type Bird = { fly: () => void };

Next, you can define a function that determines whether the given parameter is an instance of the Fish type.

function isFish(animal: Fish | Bird): animal is Fish {
    return (animal as Fish).swim !== undefined;
}

Similarly, you can define a function that determines whether the given parameter is an instance of the Bird type.

function isBird(animal: Fish | Bird): animal is Bird {
    return (animal as Bird).fly !== undefined;
}

Now, inside a function, you can use the above function to check for Fish and Bird types as shown below :  

function handleAnimal(animal: Fish | Bird) {
    if (isFish(animal)) {
        console.log("It's a fish!");
        animal.swim();
    }

    if (isBird(animal)) {
        console.log("It's a bird!");
        animal.fly();
    }
}

Next pass Bird and Fish type objects to handleAnimal function as shown below

const fish: Fish = {
    swim: () => console.log("Fish is swimming"),
};
handleAnimal(fish);

const bird: Bird = {
    fly: () => console.log("Bird is flying"),
};
handleAnimal(bird); 

In this way, you can use a custom type predicate for narrowing in TypeScript.


Discover more from Dhananjay Kumar

Subscribe to get the latest posts sent to your email.

Published by Dhananjay Kumar

Dhananjay Kumar is founder of NomadCoder and ng-India

2 thoughts on “How to use TypeScript Custom Predicate for Narrowing

Leave a comment

Discover more from Dhananjay Kumar

Subscribe now to keep reading and get access to the full archive.

Continue reading