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:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    class letters { 
        private a;
      
        constructor(alphabet){ 
            this.a = alphabet;
        
     
        getA(){
            return this.a;
        }
    const l = new letters("gfg"); 
    console.log(l.getA()); 

    chevron_right

    
    

  • 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:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    class letters {
        #a;
     
        constructor(alphabet){
            this.#a = alphabet;
        }
     
        getA(){
            return this.#a;
        }
    }
    const l = new letters("gfg");
    console.log(l.getA());            

    chevron_right

    
    

    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.

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.