Open In App

How to use Type Guards in TypeScript ?

Last Updated : 14 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Type Guards are a TypeScript feature that allows developers to narrow down the type of a variable within a conditional block. They are particularly useful when dealing with union types or when the type of a variable cannot be determined by TypeScript’s static analysis alone.

Type Guards provide a way to ensure type safety at runtime, thereby preventing potential errors.

There are several types of type guards which are described as follows:

Using typeof Type Guards

The typeof operator in TypeScript can be used to check the type of a variable using the typeof operator. When used in a conditional statement, it acts as a Type Guard by narrowing down the type of the variable.

Example: To demonstrate the typeof name === ‘string’ check acts as a Type Guard, allowing TypeScript to infer that name is of type string within the conditional block.

Javascript
function greet(name: string | number) {
    if (typeof name === 'string') {
        console.log(`Hello, ${name.toUpperCase()}!`);
    } else {
        console.log(`Hello, ${name}!`);
    }
}

greet('John');
greet(42);

Output:

"Hello, JOHN!" 
"Hello, 42!"

Using instanceof Type Guards

The instanceof operator checks if an object is an instance of a particular class or constructor function. It can be used as a Type Guard to narrow down the type of an object. Here’s how you can use instanceof:

Example: To demonstrate infering the correct type with in each conditional block and finding the instanceof Dog and instanceof Cat act as Type Guards.

Javascript
class Animal {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
}

class Dog extends Animal {
    breed: string;
    constructor(name: string, breed: string) {
        super(name);
        this.breed = breed;
    }
}

class Cat extends Animal {
    color: string;
    constructor(name: string, color: string) {
        super(name);
        this.color = color;
    }
}

function displayInfo(animal: Dog | Cat) {
    if (animal instanceof Dog) {
        console.log(
            `This is a dog named ${animal.name},
                    breed: ${animal.breed}`
        );
    } else {
        console.log(
            `This is a cat named ${animal.name},
                    color: ${animal.color}`
        );
    }
}

const dog = new Dog('Buddy', 'Labrador');
const cat = new Cat('Whiskers', 'Gray');

displayInfo(dog);
displayInfo(cat);

Output:

"This is a dog named Buddy,  breed: Labrador"
"This is a cat named Whiskers, color: Gray"

Creating Custom Type Guards

Custom Type Guards are user-defined functions that return a boolean value based on some condition. These functions can be used to check complex conditions and narrow down the type of a variable. Here’s an example of a custom type guard

Example: To demonstrate checking the custom type guard that checks if the vehicle object has a model property. If it does, the function returns true, indicating that the object is of type Car. This custom type guard is then used within the displayVehicleInfo function to ensure type safety.

Javascript
interface Car {
    make: string;
    model: string;
}

interface Truck {
    make: string;
    capacity: number;
}

function isCar(vehicle: Car | Truck): vehicle is Car {
    return 'model' in vehicle;
}

function displayVehicleInfo(vehicle: Car | Truck) {
    if (isCar(vehicle)) {
        console.log(
            `This is a car made by ${vehicle.make},
                 model: ${vehicle.model}`);
    } else {
        console.log(
            `This is a truck made by ${vehicle.make},
                  capacity: ${vehicle.capacity}`
        );
    }
}

const car: Car = {
    make: 'Toyota',
    model: 'Corolla'
};
const truck: Truck = {
    make: 'Ford',
    capacity: 1000
};

displayVehicleInfo(car);
displayVehicleInfo(truck);

Output:

"This is a car made by Toyota, model: Corolla" 
"This is a truck made by Ford, capacity: 1000"


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads