Inheriting in TypeScript code example
Example 1: ts extends
class Animal {
name: string;
constructor(theName: string) { this.name = theName; }
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Snake extends Animal {
constructor(name: string) { super(name); }
move(distanceInMeters = 5) {
console.log("Slithering...");
super.move(distanceInMeters);
}
}
class Horse extends Animal {
constructor(name: string) { super(name); }
move(distanceInMeters = 45) {
console.log("Galloping...");
super.move(distanceInMeters);
}
}
let sam = new Snake("Sammy the Python");
let tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
Example 2: class inheritance in typescript
class Info {
protected name: string ;
constructor(n:string){
this.name = n ;
};
describe(){
console.log(`Your name is ${this.name}`);
}
}
class Detail extends Info{
constructor(name:string, public age:number){
super(name);
}
findAge(){
console.log(`${this.name} age is ${this.age}`)
}
}
const b = new Detail('jank', 23);
b.describe();
b.findAge();