You are on page 1of 4

property in typescript:

-----------------------
*property can be used to set or get private field of a class
*property declaration requires set and get accessors
*syntax:
public set <propertyname>(para:type)
{ set private field
calculation|validation for private field
}

public get <propertyname>():type


{
return private field
}
*property is a combination of 2 blocks
1.set block--writting|assinging a value to property will execute set block
2.get block--reading a property will execute get block

employee class
|
empno
da
sal---calculate da as 30%sal-->declare as property

eg:
---
*create a new file
propertydemo.ts
|
class employee
{
private _empno:number;
private _sal:number;
private _da:number;

constructor(empno:number)
{
this._empno=empno;
}
//property declaration
public set sal(sal1:number)
{
this._sal=sal1;
this._da=this._sal*0.3;
}
public get sal():number
{
return this._sal;
}
display()
{
console.log(`empno:${this._empno} sal:${this._sal} da:${this._da}`);
}
}
//create an object
let eobj=new employee(100);
eobj.sal=20000;//set block will be executed,da will be calculated
eobj.display();
eobj.sal=eobj.sal+10000;//get block ad set block execution
eobj.display();

*goto terminal
>tsc propertydemo.ts
propertydemo.ts:12:16 - error TS1056: Accessors are only available when targeting
ECMAScript 5 and higher.

propertydemo.ts:17:16 - error TS1056: Accessors are only available when targeting


ECMAScript 5 and higher.

17 public get sal():number ~~~

Found 2 errors.

note:
-----
*typescript compiler[tsc] by default will target to ECMAScript3[ES3],ES3 doesn't
support
set and get accessors[i.e property concept],this the reason for above errors

*typescript compiler can be set with ES version using target option[-t]

syntax:
tsc <tsfilename> -t "ESversion"

*goto terminal
>tsc propertydemo.ts -t es5
tsc will convert typescript code into ecmascript5

>node propertydemo
empno:100 sal:20000 da:6000
empno:100 sal:30000 da:9000

*property looks like public field,but internal execution will be


like methods
*whenever there is a requirement of calculation|validation based on
private field of a class then go with property concept

You might also like