TypeScript Implements
The implements keyword makes a class promise to match an interface. The compiler checks that the class provides every member the interface names.
Implement an interface
Receipt promises the Printer interface. The class provides the print method the interface names.
interface Printer {
print(): string;
}
class Receipt implements Printer {
print(): string {
return "Receipt ready";
}
}
const printer: Printer = new Receipt();
console.log(printer.print());Miss a member
This class claims the Printer interface and provides no print method. The compiler refuses the class.
interface Printer {
print(): string;
}
class Receipt implements Printer {
}Example
interface Greeter {
greet(): string;
}
class EnglishGreeter implements Greeter {
greet(): string {
return "Hello";
}
}
class SpanishGreeter implements Greeter {
greet(): string {
return "Hola";
}
}
const greeters: Greeter[] = [new EnglishGreeter(), new SpanishGreeter()];
for (const greeter of greeters) {
console.log(greeter.greet());
}Key points
- The implements keyword follows the class name and the interface name.
- A class that implements an interface must provide every member of that interface.
- A missing member is a compile error.
- A variable typed as an interface can hold any class that implements it.
- One interface can be implemented by many different classes.
In this example, the Greeter interface names one greet method. Two classes implement the interface in different ways. The array holds both classes under the Greeter type. The loop calls greet on each item, and each class answers in its own words.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
What happens when a class claims an interface but misses one of its members?