Open In App

TypeScript instanceof narrowing Type

Last Updated : 02 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

TypeScript instanceof operator is used for type narrowing, allowing us to check whether an object is an instance of a specific class or constructor function. When we use instanceof in a conditional statement, TypeScript narrows the type of a variable based on the result of the check.

Syntax:

if (objectToCheck instanceof ConstructorFunction) {
// Code block to execute if 'objectToCheck' is an instance of 'ConstructorFunction'
}

Where:

  • objectToCheck is the object you want to check if it’s an instance of a specific class or constructor function.
  • ConstructorFunction: This is the constructor function or class constructor that you want to check against. If objectToCheck is an instance of ConstructorFunction, the condition will be true, and TypeScript will narrow the type of objectToCheck accordingly.
  • instanceof is a keyword used for type narrowing, allowing you to check whether an object is an instance of a specific class or constructor function.

Example 1: In this example, We have two classes, Car and Bicycle, each with its own methods (start and pedal).The startVehicle function takes a parameter called vehicle, which can be either a Car or a Bicycle. Inside the function, we use instanceof to check the type of vehicle. If the vehicle is an instance of a Car, it narrows the type to Car, allowing us to call the start method. If the vehicle is an instance of a Bicycle, it narrows the type to Bicycle, allowing us to call the pedal method.

Javascript




class Car {
    start() {
        console.log("Car started");
    }
}
  
class Bicycle {
    pedal() {
        console.log("Bicycle pedaling");
    }
}
  
function startVehicle(vehicle: Car | Bicycle) {
    if (vehicle instanceof Car) {
      
        // Inside this block, 'vehicle' 
        // is narrowed to type 'Car'
        vehicle.start();
    } else {
      
        // Inside this block, 'vehicle' is 
        // narrowed to type 'Bicycle'
        vehicle.pedal();
    }
}
  
const myCar = new Car();
const myBicycle = new Bicycle();
  
startVehicle(myCar);
startVehicle(myBicycle);


Output:

z37

Example 2: In this example,We have a hierarchy of classes: Animal, Dog, and Cat. The animalSound function takes an Animal as its argument. Inside the function, we use instanceof to check whether the animal is an instance of Dog or Cat.If it’s a Dog, the type of animal is narrowed to Dog, and we can call speak on it to bark.If it’s a Cat, the type of animal is narrowed to Cat, and we can call speak on it to meow.Otherwise, if it’s not a Dog or Cat, it remains of type Animal, and we call the generic speak method.

Javascript




class Animal {
    speak() {
        console.log("Animal makes a sound");
    }
}
  
class Dog extends Animal {
    speak() {
        console.log("Dog barks");
    }
}
  
class Cat extends Animal {
    speak() {
        console.log("Cat meows");
    }
}
  
function animalSound(animal: Animal) {
    if (animal instanceof Dog) {
      
        // Inside this block, 'animal' 
        // is narrowed to type 'Dog'
        animal.speak(); // Calls Dog's speak method
    } else if (animal instanceof Cat) {
      
        // Inside this block, 'animal' 
        // is narrowed to type 'Cat'
        animal.speak(); // Calls Cat's speak method
    } else {
      
        // Inside this block, 'animal' 
        // is still of type 'Animal'
        animal.speak(); // Calls Animal's speak method
    }
}
  
const dog = new Dog();
const cat = new Cat();
const genericAnimal = new Animal();
  
animalSound(dog);
animalSound(cat);
animalSound(genericAnimal);


Output: z38

Conclusion: in this article we have seen ‘instanceof’ narrowing Type and it’s syntax. It always returns a boolean value. It helps in cheking whether the object is an instaceof a class or not.

Reference: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#instanceof-narrowing



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads