It is possible to inherit one interface from another using the extends
keyword. This makes it possible to extend multiple interfaces in Typescript.
Let’s look at how to implement this in Typescript.
interface Name {
name: string;
}
interface Weight {
weight: number;
}
interface Height {
height: number;
}
interface Animal extends Name, Weight, Height {}
let animal: Animal = {
name: "Bruno",
weight: 5,
height: 3,
};
console.log(animal); // {name: 'Bruno', weight: 5, height: 3}
In the above example, we have four interfaces, Name
, Weight
, Height
, and Animal
. The Animal
interface inherits Name
, Weight
, Height
interfaces using the extends keyword.
Notice, when creating the animal
object we have defined the fields name
, weight
, and height
. This is because interface Animal
extends all three interfaces, making it necessary for us to declare them.
If you miss any of the fields while creating the object, TypeScript will throw an error. Let’s say we skipped initializing height
property.
let animal: Animal = {
// Property 'height' is missing in type '{ name: string; weight: number; }' but required in type 'Animal'.
name: "Bruno",
weight: 5,
};
The above code will throw an error, Property 'height' is missing in type '{ name: string; weight: number; }' but required in type 'Animal'.
We can also write the above implementation in a different way. Let’s say interface Weight
extends from interface Name
and Height
interface extends weight for some reason. Then we write the above code as follows.
interface Name {
name: string;
}
interface Weight extends Name {
weight: number;
}
interface Height extends Weight {
height: number;
}
Now, the Animal
interface can simply inherit the Height
interface to get all the properties of the Name
and Weight
interfaces.
interface Animal extends Height {}
let animal: Animal = {
name: "Bruno",
weight: 5,
height: 3,
};
console.log(animal); // {name: 'Bruno', weight: 5, height: 3}