Hone

Lessons · TypeScript · implements an interface

An interface describes; a class implements and builds

class Dog implements Animal promises that Dog has every member Animal declares, and the compiler checks it. Any object with the right shape satisfies Animal, whether it says implements or not.

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

Code that depends on Animal can be handed a Dog, a Cat, or a plain object in a test, and the compiler guarantees each has what the code will call. That is how modules stay swappable.

How to think about it

Write the interface from the caller's point of view: what will be called on it? Then implement it in classes, and let functions accept the interface rather than a concrete class.

Worked example

interface Animal { name: string; speak(): string; }
The shape callers rely on.
class Dog implements Animal {
Must have every member Animal declares.
  constructor(public name: string) {}
  speak() { return this.name + ' says Woof'; }
}
const plain: Animal = { name: 'Cat', speak: () => 'Meow' };
Any object of the right shape counts.
console.log(new Dog('Rex').speak(), plain.speak());
Rex says Woof Meow

Your turn

Promise that Robot has Animal's members.

class Robot  Animal {
  name = 'R2';
  speak() { return 'Beep'; }
}

The trap

Thinking implements adds the members. It only checks; a class that says implements Animal and forgets speak() is a compile error, not a class with a free speak().

Practise implements an interface on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.