Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Using instanceof for Type Guards | Type Guard Foundations
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

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 4

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Awesome!

Completion rate improved to 5.88

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

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 4
some-alt