Typescript > Interfaces

Extending interfaces in Typescript

How to extend an interface in TypeScript?


In previous post, we learnt about Array and Class type interfaces in TypeScript. In this post, we shall learn how to extend the interface to make it reusable or separating them based on entities.

To learn about basics of Interface, click here.

Extending interfaces in TypeScript

Extending single interface

In below code snippet, we have IPlayer interface and IPlayerAddress interface. IPlayerAddress interface extends IPlayer that means that the properties and functions of IPlayer would also be available to the instance of IPlayerAddress.

After defining the interfaces, we have instantiated the IPlayerAddress interface and set properties of both IPlayer and IPlayerAddress interface.

interface IPlayer {
    name: string;
}

interface IPlayerAddress extends IPlayer {
    address: string;
}

// using the interface that extends another interface
var player = <IPlayerAddress>{};
player.name = "Sheo Narayan";
player.address = "Hyderabad";
alert(JSON.stringify(player));

Compiling above TypeScript code results following JavaScript code.

var player = {};
player.name = "Sheo Narayan";
player.address = "Hyderabad";
alert(JSON.stringify(player));

Extending multiple interfaces

To extend multiple interface, simply separate interface name after extends keyword with comma (,) like shown below.

interface IPlayerCountry extends IPlayerAddress, IPlayer {
    country: string;
}

// using the interface that extends multiple interface
var thisPlayer = <IPlayerCountry>{};
thisPlayer.name = 'Dhoni';
thisPlayer.address = 'Ranchi';
thisPlayer.country = 'India';
alert(JSON.stringify(thisPlayer));

Compiling above code gives following JavaScript code.

// using the interface that extends multiple interface
var thisPlayer = {};
thisPlayer.name = 'Dhoni';
thisPlayer.address = 'Ranchi';
thisPlayer.country = 'India';
alert(JSON.stringify(thisPlayer));

To know how to declar optional property in the Interface, read this.

 Views: 25673 | Post Order: 5



Write for us






Hosting Recommendations