1// An example of getter and setter
2class myClass {
3 private _x: number;
4
5 get x() {
6 return this._x;
7 }
8
9 // in this example we'll try to set _x to only numbers higher than 0
10 set x(value) {
11 if(value <= 0)
12 throw new Error('Value cannot be less than 0.');
13 this._x = value;
14 }
15}
16let test = new myClass();
17test.x = -1; // You'll be getting an error
1interface IPerson {
2 fullname: string
3 age: number
4}
5
6class Person {
7
8 private fullname:string;
9 private age:number;
10
11 constructor({...options}: IPerson ) {
12 this.fullname = 'jane doe'
13 this.age = 30
14 this.set(options)
15 }
16
17 get(): IPerson {
18 const data = {
19 fullname: this.fullname,
20 age: this.age
21 }
22 return data
23 }
24
25 set<T extends IPerson>({...options}: T): void {
26 this.fullname = options.fullname
27 this.age = options.age
28 }
29
30}
31
32const data = new Person({
33 fullname: 'john doe',
34 age:28
35})
36
37console.log(data.get())