Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Using instanceof for Type Guards | Type Guard Foundations
Quizzes & Challenges
Quizzes
Challenges
/
Error Handling and Type Guards in TypeScript

bookUsing instanceof for Type Guards

12345678910111213141516171819202122232425
class Animal { speak() { console.log("Some generic animal sound"); } } class Dog extends Animal { bark() { console.log("Woof!"); } } function makeSound(creature: Animal) { if (creature instanceof Dog) { creature.bark(); // Safe: TypeScript knows creature is a Dog } else { creature.speak(); } } const genericAnimal = new Animal(); const petDog = new Dog(); makeSound(genericAnimal); // Output: Some generic animal sound makeSound(petDog); // Output: Woof!
copy

When working with class hierarchies in TypeScript, the instanceof operator is a powerful tool for creating type guards that distinguish between instances of different classes. The instanceof operator checks whether an object was created by a specific class constructor or inherits from it, allowing you to safely access properties and methods unique to that subclass.

For example, if you have a function that accepts a parameter of type Animal, but you want to perform operations specific to a Dog, you can use creature instanceof Dog to narrow the type. This enables TypeScript to understand that within that block, creature is a Dog, and you can safely call methods like bark().

However, it is important to understand the limitations of instanceof. It only works with values that are actual class instances—objects created using the new keyword from a class constructor. It does not work with interfaces, because interfaces are a compile-time construct and do not exist at runtime. Therefore, you cannot use instanceof to check if an object implements a specific interface.

Additionally, instanceof will not recognize plain objects that merely match the shape of a class or interface. It depends on the object's prototype chain, so objects created with object literals or factory functions will not pass an instanceof check unless they are explicitly constructed using the class.

Use instanceof when you need to differentiate between class-based types, especially in codebases that use inheritance or polymorphism. For interfaces or plain objects, you will need to use other type guard techniques.

question mark

When is it appropriate to use instanceof for type checking in TypeScript?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 4

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Suggested prompts:

Can you explain more about how type guards work in TypeScript?

What are some alternatives to `instanceof` for checking interfaces?

Can you give examples of when `instanceof` might not work as expected?

Awesome!

Completion rate improved to 5.88

bookUsing instanceof for Type Guards

Scorri per mostrare il menu

12345678910111213141516171819202122232425
class Animal { speak() { console.log("Some generic animal sound"); } } class Dog extends Animal { bark() { console.log("Woof!"); } } function makeSound(creature: Animal) { if (creature instanceof Dog) { creature.bark(); // Safe: TypeScript knows creature is a Dog } else { creature.speak(); } } const genericAnimal = new Animal(); const petDog = new Dog(); makeSound(genericAnimal); // Output: Some generic animal sound makeSound(petDog); // Output: Woof!
copy

When working with class hierarchies in TypeScript, the instanceof operator is a powerful tool for creating type guards that distinguish between instances of different classes. The instanceof operator checks whether an object was created by a specific class constructor or inherits from it, allowing you to safely access properties and methods unique to that subclass.

For example, if you have a function that accepts a parameter of type Animal, but you want to perform operations specific to a Dog, you can use creature instanceof Dog to narrow the type. This enables TypeScript to understand that within that block, creature is a Dog, and you can safely call methods like bark().

However, it is important to understand the limitations of instanceof. It only works with values that are actual class instances—objects created using the new keyword from a class constructor. It does not work with interfaces, because interfaces are a compile-time construct and do not exist at runtime. Therefore, you cannot use instanceof to check if an object implements a specific interface.

Additionally, instanceof will not recognize plain objects that merely match the shape of a class or interface. It depends on the object's prototype chain, so objects created with object literals or factory functions will not pass an instanceof check unless they are explicitly constructed using the class.

Use instanceof when you need to differentiate between class-based types, especially in codebases that use inheritance or polymorphism. For interfaces or plain objects, you will need to use other type guard techniques.

question mark

When is it appropriate to use instanceof for type checking in TypeScript?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 4
some-alt