properties in typescript 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: define object properties typescript

interface ISomeObject {
  subPropertie1: string,
  subPropertie2: number,
}

interface IProperties {
  property1: string,
  property2: boolean,
  property3: number[],
  property4: ISomeObject,
  property5: ISomeObject[],
}

function (args:IProperties): void {		// Sample Usage
  console.log(args.property1);
}

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