Instanceof Type Guard in TypeScript: A Complete Guide

Updated: January 8, 2024 By: Guest Contributor Post a comment

Overview

TypeScript’s ‘instanceof’ type guard is a robust feature for narrowing down types through the prototype chain, ensuring your code is type-safe and maintainable.

Introduction to Type Guards

Type guards are a fundamental concept in TypeScript that allow developers to narrow down the type of a variable within a conditional block. The ‘instanceof’ operator is one such guard, enabling a type-safe way of checking whether an object is an instance of a particular class. Understanding and employing ‘instanceof’ type guards can greatly enhance code readability, maintainability, and type safety. In this guide, we take an in-depth look at how to use ‘instanceof’ type guards through illustrative examples.

Basic Usage of ‘instanceof’

class Animal {
    breathe() { console.log('Breathing...'); }
}

class Dog extends Animal {
    bark() { console.log('Woof!'); }
}

let pet: Animal = new Dog();

if (pet instanceof Dog) {
    pet.bark(); // Safe to call because 'pet' is confirmed to be of type 'Dog'
}

Advanced Type Guard Techniques

Utilizing ‘instanceof’ with interfaces can be tricky, as interfaces do not exist at runtime. However, by incorporating a ‘type’ property or using classes that implement interfaces, you can create flexible and type-safe conditions.

interface Bird {
    fly(): void;
}

class Eagle implements Bird {
    type = 'eagle';
    fly() { console.log('Flying high!'); }
}

class Penguin implements Bird {
    type = 'penguin';
    fly() { console.log('I wish I could fly...'); }
}

function letBirdFly(bird: Bird) {
    if ('fly' in bird) {
        bird.fly();
    }
}

let snowy = new Eagle();
letBirdFly(snowy); // Outputs: Flying high!

Conclusion

This guide provided insight into the effective use of ‘instanceof’ type guards in TypeScript. By leveraging these, developers can write more robust and predictably typed code, enhancing the quality of their TypeScript projects.