typescript getter rsetter code example

Example 1: getter and setter in typescript

// An example of getter and setter
class myClass {
	private _x: number;
  
  	get x() {
    	return this._x;
    }
  
 	// in this example we'll try to set _x to only numbers higher than 0
  	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; // You'll be getting an error

Example 2: typescript getter setter

interface IPerson {
  fullname: string
  age: number
}

class Person {
  
 private fullname:string;
 private age:number;

 constructor({...options}: IPerson ) {
  this.fullname = 'jane doe'
  this.age = 30
  this.set(options)
 }

 get(): IPerson {
   const data = {
     fullname: this.fullname,
     age: this.age
   }
   return data
 }

 set<T extends IPerson>({...options}: T): void {
   this.fullname = options.fullname
   this.age = options.age
 }

}

const data = new Person({
  fullname: 'john doe',
  age:28
})

console.log(data.get())