typscript set function on class atribute 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: 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();