Animal and Tiger class inheritance in TypeScript
9 An animal, and a tiger that roars
easyWrite an animal class with a name and a species. Then write a tiger class that extends it and adds a roar() method.
Stuck? Three hints, smallest first
- 1. The subclass can set the species itself, so its constructor need only take a name.
- 2. That is a common pattern: the child knows something fixed about itself and passes it up.
- 3. Nothing stops you overriding a method too, but here you are only adding one.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
class Animal {
constructor(
public name: string,
public species: string,
) {}
describe(): string {
return `${this.name} is a ${this.species}`;
}
}
class Tiger extends Animal {
// The species is fixed for a tiger, so the caller does not supply it.
constructor(name: string) {
super(name, 'tiger');
}
roar(): string {
return `${this.name} roars!`;
}
}
const t = new Tiger('Shere Khan');
const generic = new Animal('Rex', 'dog');
console.log(t.describe());
console.log(t.roar());
console.log(generic.describe());
// roar exists only on Tiger:
// generic.roar(); // Property 'roar' does not exist on type 'Animal'.
test('species was filled in by the subclass', t.species, 'tiger');
test('inherited describe', t.describe(), 'Shere Khan is a tiger');
test('the new method', t.roar(), 'Shere Khan roars!');
test('the parent still works alone', generic.describe(), 'Rex is a dog');
test('a Tiger is an Animal', t instanceof Animal, true);
Output
Tiger’s constructor takes one argument and passes two up. That is worth noticing: a subclass often exists precisely to fix one of the parent’s values, which makes the class easier to call than the parent it came from.