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(){Â Â Â Â Â Â Â Âreturnthis.a;Â Â Â Â}}Âconst l =newletters("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(){Â Â Â Â Â Â Â Âreturnthis.#a;Â Â Â Â}}const l =newletters("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. |
