Implementing Interfaces
In this page:
Basic Implementation
Adding implements InterfaceName to a class declaration requires that class to satisfy every property and method the interface defines. If the class is missing something the interface requires, or has the wrong type for it, TypeScript reports a compile error.
Example: Basic Implementation
interface Greetable {
name: string;
}
class Person implements Greetable {
name: string;
constructor(name: string) {
this.name = name;
}
}
console.log(new Person("Ana").name);
Implementing Methods
A class implementing an interface must provide a compatible implementation for every required method, matching the interface's declared parameter and return types. The class's own implementation can be more specific, but never less capable, than what the interface promises.
Example: Implementing Methods
interface Speaker {
speak(): string;
}
class Robot implements Speaker {
speak(): string {
return "Beep boop";
}
}
console.log(new Robot().speak());
Implementing Multiple Interfaces
A single class can implement multiple interfaces at the same time, simply by listing them comma-separated after implements. This lets a class satisfy several independent contracts at once, such as being both Comparable and Serializable.
Example: Implementing Multiple Interfaces
interface Flyable {
fly(): string;
}
interface Swimmable {
swim(): string;
}
class Duck implements Flyable, Swimmable {
fly() { return "Flying"; }
swim() { return "Swimming"; }
}
const duck = new Duck();
console.log(duck.fly(), duck.swim());
Using Implemented Classes
Any instance of a class that implements a given interface can be used anywhere that interface type is expected, regardless of the class's own concrete name. This is what makes interfaces useful for writing code that depends on a shape rather than a specific implementation.
Example: Using Implemented Classes
interface Speaker {
speak(): string;
}
class Robot implements Speaker {
speak() { return "Beep"; }
}
function announce(speaker: Speaker) {
console.log(speaker.speak());
}
announce(new Robot());
Implementing Extended Interfaces
When a class implements an interface that itself extends other interfaces, the class must satisfy both the requirements added directly by that interface and everything it inherited from its parents. TypeScript checks the whole combined contract, not just the interface's own declared members.
Example: Implementing Extended Interfaces
interface Named {
name: string;
}
interface Greetable extends Named {
greet(): string;
}
class Person implements Greetable {
constructor(public name: string) {}
greet() { return `Hi, I'm ${this.name}`; }
}
console.log(new Person("Zoe").greet());
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: