TypeScript - Access Modifier & get/set
Access Modifier:
private - within the class
public - access from anywhere
protected - within the class and subclasses.
Note: Most of the time if compile time error also, It will generate the file and we can run the file.
How to avoid this ?
1. Delete the js file whatever created earlier. using below command.
Eg. del Customer.js
2. Use below command to not generate the .js file if any compilation error .
Command : tsc -noEmitOnError Customer.ts
Accessors:
Class Customer{
private firstName : string;
private lastName : string;
public getFirstName(): string(){
return this.firstName;
}
public setFirstName(theFirst: string): void {
this.firstName : theFirst;
}
}
Using Get/Set:
* get/set accessors is only supported in ES5 and higher.
* you have to set the compiler flag inorder to compile the code.
Syntax to compile:
tsc --target ES5 -noEmitOnError Customer.ts
Example:
Class Customer{
private _firstName: string;
private _lastName: string;
public get firstName(): string(){
return this._firstName;
}
public set firstName(value: string){
this._firstName = value;
}
}
private - within the class
public - access from anywhere
protected - within the class and subclasses.
Note: Most of the time if compile time error also, It will generate the file and we can run the file.
How to avoid this ?
1. Delete the js file whatever created earlier. using below command.
Eg. del Customer.js
2. Use below command to not generate the .js file if any compilation error .
Command : tsc -noEmitOnError Customer.ts
Accessors:
Class Customer{
private firstName : string;
private lastName : string;
public getFirstName(): string(){
return this.firstName;
}
public setFirstName(theFirst: string): void {
this.firstName : theFirst;
}
}
Using Get/Set:
* get/set accessors is only supported in ES5 and higher.
* you have to set the compiler flag inorder to compile the code.
Syntax to compile:
tsc --target ES5 -noEmitOnError Customer.ts
Example:
Class Customer{
private _firstName: string;
private _lastName: string;
public get firstName(): string(){
return this._firstName;
}
public set firstName(value: string){
this._firstName = value;
}
}
Comments
Post a Comment