Close

TypeScript - Interface Extending Interfaces

[Updated: Sep 13, 2018, Created: Sep 13, 2018]

In TypeScript, an interface can extend other interfaces as well. One interface can extend multiple interfaces at a time.

Example

extending-interfaces.ts

interface Component {
    w: number;
    h: number;
    enableEvents(enable: boolean): void;
}

interface Button extends Component {
    label: string;
}

//implementing extended interface
class RadioButton implements Button {
    h: number;
    label: string;
    w: number;
    private enable: boolean;

    constructor(h: number, w: number, label: string) {
        this.h = h;
        this.w = w;
        this.label = label;
    }

    enableEvents(enable: boolean): void {
        this.enable = enable;
    }
}

let radioButton: Button = new RadioButton(100, 20, "test");
radioButton.enableEvents(true)
console.log(radioButton);

Output

RadioButton { h: 100, w: 20, label: 'test', enable: true }

Compiled JavaScript (--target es):

extending-interfaces.js

//implementing extended interface
class RadioButton {
    constructor(h, w, label) {
        this.h = h;
        this.w = w;
        this.label = label;
    }
    enableEvents(enable) {
        this.enable = enable;
    }
}
let radioButton = new RadioButton(100, 20, "test");
radioButton.enableEvents(true);
console.log(radioButton);

An extended interface can also be used as described properties:

extending-interfaces-describing-properties.ts

interface Component {
    w: number;
    h: number;
}

interface Button extends Component {
    label: string;
    onClick(): void;
}

//extended interface to describe properties
let btn: Button = {
    w: 200, h: 20, label: "test", onClick: function () {
         console.log("button clicked")
    }
};
console.log(btn);
btn.onClick();

Output

{ w: 200, h: 20, label: 'test', onClick: [Function: onClick] }
button clicked

An interface can extend multiple interfaces:

extending-multiple-interfaces.ts

interface Component {
    w: number;
    h: number;
}

interface Clickable {
    onClick(): void;
}

interface Button extends Component, Clickable {
    label: string;
}

let btn: Button = {
    w: 100, h: 20, label: "test", onClick: function () {
        console.log("button clicked");
    }
};
console.log(btn);
btn.onClick();

Output

{ w: 100, h: 20, label: 'test', onClick: [Function: onClick] }
button clicked

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.0.3
Interface Extending Interfaces Example Select All Download
  • typescript-extending-interfaces
    • extending-interfaces.ts

    See Also