instanceof
- TypeScript course
- Advanced
- Lesson 27/57
- 4 min
Learn class narrowing with instanceof.
instanceof
The instanceof operator checks whether an object is an instance of a specific class (or its superclass). An if (animal instanceof Cat) condition checks the prototype chain and lets TypeScript narrow the type to Cat. It is used for narrowing in class-based hierarchies.
class Cat { meow() {} }
class Dog { bark() {} }
function speak(animal: Cat | Dog) {
if (animal instanceof Cat) {
animal.meow(); // Cat
} else {
animal.bark(); // Dog
}
}Class hierarchy
instanceof works only with classes; it cannot be used with interfaces because interfaces have no runtime representation. In a class hierarchy, instanceof treats subclass instances as instances of the superclass too.
class Animal {}
class Cat extends Animal { meow() {} }
const c: Animal = new Cat();
if (c instanceof Cat) {
c.meow(); // Cat
}
// Does not work with interfaces:
// if (c instanceof Pet) ... // error if Pet is an interfacePractice Separate classes with instanceof
Define Cat (with a meow method) and Dog (with a bark method) classes. Write a speak(animal: Cat | Dog): string function. If animal instanceof Cat, return "meow"; otherwise return "bark". Print results via console.log(speak(new Cat())) and console.log(speak(new Dog())).
Starter code
// Cat sınıfını (meow yöntemiyle) tanımla
// Dog sınıfını (bark yöntemiyle) tanımla
// speak(animal: Cat | Dog): string fonksiyonunu instanceof ile yaz
// speak(new Cat()) ve speak(new Dog()) sonuçlarını yazdırSample solution
class Cat {
meow() {}
}
class Dog {
bark() {}
}
function speak(animal: Cat | Dog): string {
if (animal instanceof Cat) {
return "meow";
}
return "bark";
}
console.log(speak(new Cat()));
console.log(speak(new Dog()));Expected output
meow bark
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the instanceof operator check?
- The equality of two values
- The presence of a property
- The runtime type string of a value
- The prototype chain of an object Correct answer
Explanation: instanceof checks an object's prototype chain and returns whether it is an instance of a specific class; TypeScript uses this to narrow the type.
2 Class check with instanceof
class Cat { meow() {} }
class Dog { bark() {} }
function speak(a: Cat | Dog) {
if (____) {
a.meow();
} else {
a.bark();
}
}
class Cat { meow() {} }
class Dog { bark() {} }
function speak(a: Cat | Dog) {
if (a instanceof Cat) {
a.meow();
} else {
a.bark();
}
}
Explanation: instanceof Cat checks whether a is an instance of the Cat class via the prototype chain; inside the condition a is narrowed to Cat.
3 instanceof parts
| Term | Meaning |
|---|---|
instanceof |
checks prototype chain |
instanceof Cat |
narrows to Cat class |
Sınıf (class) |
can be used with instanceof |
Interface |
cannot be used with instanceof |