A class in TypeScript can implement multiple interfaces using the implements
keyword with the names of interfaces separated by a comma.
interface Name {
name: string;
}
interface Weight {
weight: number;
}
interface Height {
height: number;
}
class Animal implements Name, Weight, Height {
name: string;
height: number;
weight: number;
constructor(name: string, weight: number, height: number) {
this.name = name;
this.weight = weight;
this.height = height;
}
}
let animal = new Animal("Bruno", 5, 3);
console.log(animal); // Animal {name: 'Bruno', weight: 5, height: 3}
In this example, we have three interfaces Name
, Weight
, and Height
. The class Animal
implements all three interfaces using the implements
keyword.
Notice, the class Animal
includes all the properties that are present in the implemented interfaces. If we miss any property, TypeScript will complain about it. Suppose, if I miss declaring name
property while declaring the class, TypeScript will throw an error.
// NOT ALLOWED
class Animal implements Name, Weight, Height {
// Class 'Animal' incorrectly implements interface 'Name'.
height: number;
weight: number;
constructor(weight: number, height: number) {
this.weight = weight;
this.height = height;
}
}
In this case, TypeScript will throw an error, Class 'Animal' incorrectly implements interface 'Name'. Property 'name' is missing in type 'Animal' but required in type 'Name'.
It is also possible that an interface might inherit from another interface. For example,
interface Name {
name: string;
}
interface Weight extends Name {
weight: number;
}
interface Height extends Weight {
height: number;
}
class Animal implements Height {
name: string;
height: number;
weight: number;
constructor(name: string, weight: number, height: number) {
this.name = name;
this.weight = weight;
this.height = height;
}
}
let animal = new Animal("Bruno", 5, 3);
console.log(animal); // Animal {name: 'Bruno', weight: 5, height: 3}
As you can see, interface Weight
extends the interface Name
and interface Height
extends the interface Weight
. When declaring class Animal
we only implement Height
interface but all the properties of Name
and Weight
must be implemented by class Animal
.