Close

TypeScript - Class Implementing Interfaces

[Last Updated: Apr 19, 2019]

In TypeScript, a class can implement interfaces to enforce particular contracts (similar to languages like Java and C#).

Example

class-implementing-interface.ts

interface Task{
    name: String; //property
    run(arg: any):void; //method
}

class MyTask implements Task{
    name: String;
    constructor(name: String) {
        this.name = name;
    }

    run(arg: any): void {
        console.log(`running: ${this.name}, arg: ${arg}`);
    }
}

let myTask: Task = new MyTask('someTask');
myTask.run("test");

Output

running: someTask, arg: test

Compiled JavaScript (--target es6):

class-implementing-interface.js

class MyTask {
    constructor(name) {
        this.name = name;
    }
    run(arg) {
        console.log(`running: ${this.name}, arg: ${arg}`);
    }
}
let myTask = new MyTask('someTask');
myTask.run("test");

Implementing multiple interfaces

class-implementing-multiple-interface.ts

interface Shape {
    draw(): void;
}

interface Editable{
    canEdit: boolean;
    commitChanges(): void;
}

class Square implements Shape, Editable{
    canEdit: boolean;
   constructor(canEdit: boolean) {
        this.canEdit = canEdit;
    }

    commitChanges(): void {
       if(this.canEdit) {
           console.log("changes committed");
       }
    }

    draw(): void {
        console.log("drawing");
    }
}

let square: Square = new Square(true);
square.draw();
square.commitChanges();



Output

drawing
changes committed

class-implementing-multiple-interface.js

class Square {
    constructor(canEdit) {
        this.canEdit = canEdit;
    }
    commitChanges() {
        if (this.canEdit) {
            console.log("changes committed");
        }
    }
    draw() {
        console.log("drawing");
    }
}
let square = new Square(true);
square.draw();
square.commitChanges();

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.0.3
Class Implementing Interfaces Select All Download
  • typescript-class-implementing-interfaces
    • class-implementing-interface.ts

    See Also