Professional Documents
Culture Documents
-----------------------
*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
}
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.
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
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