typescript implments code example
Example 1: extends vs implements in typescript
class Person {
name: string;
age: number;
walk(): void {
console.log('Walking (person Class)')
}
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
class child extends Person { }
class man implements Person {
name: string;
age: number
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
walk(): void {
console.log('Walking (man class)')
}
}
(new child('Mike', 12)).walk();
(new man('Tom', 12)).walk();
Example 2: typescript class implements interface
interface Task{
name: String;
run(arg: any):void;
}
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");