Emmanuel Akinfulubi

TypeScriptClasses and OOP

Abstract Animal class with makeSound in TypeScript

14 An abstract animal that must make a sound

easy

Write an abstract animal class with a name and an abstract makeSound(). Write a tiger and a lion that each return their own sound.

Stuck? Three hints, smallest first
  1. 1. Same shape as the shape exercise: abstract parent, concrete children.
  2. 2. A subclass that leaves out makeSound is a compile error, not a runtime surprise.
  3. 3. Loop over an array typed as the parent to show the polymorphism.

The answer, and proof it works

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)}`)
  );
}

abstract class Animal {
  constructor(public name: string) {}

  abstract makeSound(): string;

  // Shared, and it leans on the abstract method.
  introduce(): string {
    return `${this.name} says ${this.makeSound()}`;
  }
}

class Tiger extends Animal {
  override makeSound(): string { return 'roar'; }
}

class Lion extends Animal {
  override makeSound(): string { return 'growl'; }
}

class Elephant extends Animal {
  override makeSound(): string { return 'trumpet'; }
}

// A subclass that forgets makeSound will not compile:
// class Snake extends Animal {}
//       ^ Non-abstract class 'Snake' does not implement inherited abstract member.

const zoo: Animal[] = [new Tiger('Shere Khan'), new Lion('Elsa'), new Elephant('Dumbo')];

for (const a of zoo) console.log(a.introduce());

const sounds = zoo.map((a) => a.makeSound());

test('tiger', zoo[0]?.makeSound(), 'roar');
test('lion', zoo[1]?.makeSound(), 'growl');
test('elephant', zoo[2]?.makeSound(), 'trumpet');
test('shared introduce uses each own sound', zoo[1]?.introduce(), 'Elsa says growl');
test('all three sounds', sounds, ['roar', 'growl', 'trumpet']);

Output


      

The commented-out Snake is the part worth trying. Uncomment it and the build stops with a clear message. That is the difference between an abstract method and a note in a README asking people to remember.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.