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.tsclass 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(); OutputButton { 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.tsclass 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);
OutputBox { width: 200, height: 100, modal: true }
Example ProjectDependencies and Technologies Used: |