In TypeScript, a class can implement interfaces to enforce particular contracts (similar to languages like Java and C#).
Example
class-implementing-interface.tsinterface 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"); Outputrunning: someTask, arg: test
Compiled JavaScript (--target es6):
class-implementing-interface.jsclass 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.tsinterface 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();
Outputdrawing changes committed
class-implementing-multiple-interface.jsclass 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 ProjectDependencies and Technologies Used: |