In TypeScript there is a away to set a private variables using the getters and setters. You can refer the following link for its implementation:
https://www.typescriptlang.org/docs/handbook/classes.html#accessors
Below is a sample implemenation of accessing and modifying private variables in a class using the get and set keywords. Do notice that the private variable (_brand) is prefixed with a single underscore.
Let us now compile the file:
$ tsc
$
To check the console:
$ python -m SimpleHTTPServer 3000
Checking the console output:
TVS
Reference:
https://www.typescriptlang.org/docs/handbook/classes.html#accessors
Below is a sample implemenation of accessing and modifying private variables in a class using the get and set keywords. Do notice that the private variable (_brand) is prefixed with a single underscore.
// Getters and Setters
class Motorbike {
private _brand : string = "TVS";
get brand(){
return this._brand;
}
set brand(value:string){
if (value.length > 3) {
this._brand = value;
} else {
this._brand = "TVS";
}
} // end set
}
let myBike = new Motorbike();
console.log(myBike.brand);
Let us now compile the file:
$ tsc
$
To check the console:
$ python -m SimpleHTTPServer 3000
Checking the console output:
TVS
Reference:
No comments:
Post a Comment