TypeScript ยท Chapter 26 of 44

Classes Implementing Interfaces

A class can promise to follow a specific shape by using the `implements` keyword with an interface. This ensures the class provides every property and method the interface requires.

Unlike extending a class, implementing an interface does not share any actual code โ€” it only enforces a contract that the class must fulfil, which is useful for designing consistent APIs across different classes.

Syntax
interface Animal {
  makeSound(): string;
}
class Dog implements Animal {
  makeSound(): string {
    return "Woof";
  }
}

Using implements

Writing `class Dog implements Animal { ... }` tells TypeScript to check that Dog provides everything declared in the Animal interface, or produce a compile-time error.

Implementing multiple interfaces

A class can implement more than one interface at once by separating them with commas, requiring it to satisfy all of their combined requirements.

Example 1 (typescript)
interface Animal {
  makeSound(): string;
}
class Dog implements Animal {
  makeSound(): string {
    return "Woof";
  }
}
console.log(new Dog().makeSound());
Output
Woof

Dog must implement makeSound() because the Animal interface requires it.

Example 2 (typescript)
interface Flyable {
  fly(): string;
}
interface Swimmable {
  swim(): string;
}
class Duck implements Flyable, Swimmable {
  fly(): string { return "Flying"; }
  swim(): string { return "Swimming"; }
}
const d = new Duck();
console.log(d.fly(), d.swim());
Output
Flying Swimming

Duck implements two interfaces, so it must provide both fly() and swim().

Key points

  • The `implements` keyword makes a class follow an interface's shape.
  • TypeScript enforces that every required member is implemented.
  • A class can implement multiple interfaces at once.
  • Implementing an interface shares no code, only a contract.
๐Ÿ’ก Note: Use interfaces with implements to keep different classes consistent with a shared public API.

๐Ÿ“ Quick Quiz

1. Which keyword makes a class follow an interface's shape?

2. Can a class implement more than one interface?

3. What happens if a class does not implement a required interface method?