constructor in typescript code example
Example 1: constructor in typescript
class Car {
//field
engine:string;
//constructor
constructor(engine:string) {
this.engine = engine
}
//function
disp():void {
console.log("Engine is : "+this.engine)
}
}
Example 2: classes in typescript
class Info {
private name: string ;
constructor(n:string){
this.name = n ;
};
describe(){
console.log(`Your name is ${this.name}`);
}
}
const a = new Info('joyous');
a.describe();
Example 3: how to extend ts class
class Animal {
move(distanceInMeters: number = 0) {
console.log(`Animal moved ${distanceInMeters}m.`);
}
}
class Dog extends Animal {
bark() {
console.log("Woof! Woof!");
}
}
const dog = new Dog();
dog.bark();
dog.move(10);
dog.bark();Try