Difference between private keyword and private fields in TypeScript
TypeScript 3.8 supports the private keyword to declare its members private. And the private fields in TypeScript are the ones newly proposed for JavaScript. These fields are preceded by #.
Private keyword: The private keyword in TypeScript is used to mark a member private which makes it inaccessible outside the declared class. The fields are preceded by the private keyword to mark them private.
- Syntax:
private variableName
- Example:
class letters {
private a;
constructor(alphabet){
this
.a = alphabet;
}
getA(){
return
this
.a;
}
}
const l =
new
letters(
"gfg"
);
console.log(l.getA());
- Output:
gfg
Private fields: Private fields in TypeScript are the ones that have been newly added to JavaScript, the members to be declared private are preceded by a #. Private members cannot be accessed outside their class.
- Syntax:
#variableName
- Example:
class letters {
#a;
constructor(alphabet){
this
.
#a = alphabet;
}
getA(){
return
this
.
#a;
}
}
const l =
new
letters(
"gfg"
);
console.log(l.getA());
Output:
-
gfg
Hence, to implement the private keyword in runtime when compiling TypeScript to ESNext JavaScript one must consider using the private syntax # defined for JavaScript.
Difference between private keyword and private fields:
Private keyword | Private fields |
---|---|
It is a TypeScript modifier. | It is a newly added syntax by ECMA to JavaScript, which is also available in TypeScript. |
It is a compile time annotation. So, when a transpiler converts TypeScript code to JavaScript, the private keyword is removed. | The private fields remain private at runtime even after the TypeScript code gets converted to JavaScript by the transpiler. |
Contact Us