Tuesday, September 24, 2024
Google search engine
HomeLanguagesJavascriptDifference between private keyword and private fields in TypeScript

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.
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments