class typescript set code example
Example 1: getter and setter in typescript
class myClass {
private _x: number;
get x() {
return this._x;
}
set x(value) {
if(value <= 0)
throw new Error('Value cannot be less than 0.');
this._x = value;
}
}
let test = new myClass();
test.x = -1;
Example 2: 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