Lessons · TypeScript · extends, override, instanceof
extends with super first, a compatible override, and instanceof narrowing
A derived constructor calls super() before touching this. An overriding method keeps a compatible signature. instanceof narrows a base-typed variable to the subclass inside the if.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
These three rules are what let code that holds a Dog call speak() and get a string no matter which subclass it really has, while code that checks instanceof Puppy can reach what only a Puppy has.
How to think about it
In the child: super(...) first, then own fields. Override with the same parameters and return type. When you need a subclass member from a base-typed variable, guard with instanceof.
Worked example
class Dog { constructor(public name: string) {} speak(): string { return this.name + ' says Woof'; }}
class Puppy extends Dog {age = 0;A field with an initializer.
constructor(name: string) { super(name); }super first, always. speak(): string { return this.name + ' says Yip'; }Same signature: a compatible override.}
const pet: Dog = new Puppy('Bo');Typed as the base.if (pet instanceof Puppy) { console.log(pet.speak(), pet.age); }Bo says Yip 0Your turn
Reach the subclass field safely.
if (pet Puppy) {
console.log(pet.age);
}Solve one with the compiler running
The trap
Overriding speak(): string with speak(): number. The compiler refuses, because anything holding a Dog was promised a string.