TypeScript Implements in Depth
The `implements` keyword checks a class against an interface contract. A class can implement several interfaces at once and must supply every member they require.
One class implementing two interfaces
The class lists both interfaces and supplies a method for each. Both contracts hold at the same time.
interface Printable {
print(): string;
}
interface Saveable {
save(): string;
}
class Invoice implements Printable, Saveable {
print(): string {
return "printing invoice #9";
}
save(): string {
return "saved invoice #9";
}
}
const invoice = new Invoice();
console.log(invoice.print());
console.log(invoice.save());A missing member fails the whole class
This version leaves out the save method. The checker refuses the class declaration itself.
interface Printable {
print(): string;
}
interface Saveable {
save(): string;
}
class Invoice implements Printable, Saveable {
print(): string {
return "printing invoice";
}
}An interface extending another interface
The Labeled interface extends Identified, so it carries both members. The class implements the combined contract.
interface Identified {
id: number;
}
interface Labeled extends Identified {
label: string;
}
class Parcel implements Labeled {
constructor(public id: number, public label: string) {}
describe(): string {
return `#${this.id} ${this.label}`;
}
}
const parcel = new Parcel(4, "books");
console.log(parcel.describe());Example
interface Named {
label: string;
}
interface Priced {
price: number;
}
interface Tagged extends Named {
tag: string;
}
class Product implements Tagged, Priced {
constructor(
public label: string,
public tag: string,
public price: number
) {}
summary(): string {
return `${this.label} [${this.tag}] $${this.price}`;
}
}
console.log(new Product("Mug", "kitchen", 12).summary());Key points
- A class implements an interface by listing it after the `implements` keyword.
- Several interfaces are listed with commas, and the class must satisfy all of them.
- One missing member fails the whole class declaration.
- An interface can extend another interface and pass its members down.
- A class that implements the extended interface must supply the inherited members too.
- The implements list is the full contract, and the checker holds the class to every entry.
In this example, Product implements Tagged and Priced at the same time. Tagged extends Named, so the class supplies label, tag, and price to satisfy the full contract.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
A class implements two interfaces and misses one required member. What happens?