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.
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.
interface Animal {
makeSound(): string;
}
class Dog implements Animal {
makeSound(): string {
return "Woof";
}
}
console.log(new Dog().makeSound());WoofDog must implement makeSound() because the Animal interface requires it.
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());Flying SwimmingDuck 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.
