Close

TypeScript - Interface Extending Classes

[Last Updated: Sep 20, 2018]

In TypeScript, an interface can also extend classes. The inherited members do not have the implementations.

This is useful when you have a large inheritance hierarchy, but want to specify that your code works with only subclasses that have certain properties. The subclasses don't have to be related besides inheriting from the base class.

Example

interface-extending-class.ts

class Component{
    private width: number;
    private height: number;

    constructor(width: number, height: number) {
        this.width = width;
        this.height = height;
    }

    display(): void{
       console.log('displaying');
    }
}

interface Widget extends Component{
   hide(): void;
}

class Button extends Component implements Widget{
    hide(): void {
        console.log('hiding');
    }
}

let w: Widget = new Button(2,5);
console.log(w);
w.display();
w.hide();

Output

Button { width: 2, height: 5 }
displaying
hiding

The compiled JavaScript (--target es6):

class Component {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }
    display() {
        console.log('displaying');
    }
}
class Button extends Component {
    hide() {
        console.log('hiding');
    }
}
let w = new Button(2, 5);
console.log(w);
w.display();
w.hide();

Extending multiple classes

interface-extending-classes.ts

class Panel {
private width: number;
    private height: number;

    constructor(width: number, height: number) {
        this.width = width;
        this.height = height;
    }
}

class Frame {
    modal: boolean;
    constructor(modal: boolean) {
        this.modal = modal;
    }
}

interface Widget extends Panel, Frame {
    x: number;
    y: number;
}

class Box extends Panel implements Widget {
    modal: boolean;
    x: number;
    y: number;
}

let box: Box = new Box(200, 100);
box.modal = true;
console.log(box);

Output

Box { width: 200, height: 100, modal: true }

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.0.3
Interface Extending Classes Select All Download
  • typescript-interface-extending-class
    • interface-extending-class.ts

    See Also