skip to Main Content

I am trying to build a class in typescript which have few of the properties with access modifiers as in the below code.

class Coder {
    age : number;

    constructor(
    public readonly name : string,
    age : number,
    public lang : string,
    private address : string,
    protected id : number = 234
    )
    {
        this.name = name;
        this.age = age;
        this.lang = lang;
        this.address = address;
        this.id = Math.random();
    }

    getName()
    {
        return `My name is ${this.name}`;
    }
}

let coder = new Coder('Nayan', 28, 'JavaScript', 'LMP');

// Not possible as name is readOnly
// coder.name = 'Golu'; 

But the compiled code has the class with duplicate property decalation in the constructor as in the below code.

Once I try to remove any of the modifiers then the duplicate property get removed in compiled js file too (see age property).

"use strict";
class Coder {
    constructor(name, age, lang, address, id = 234) {
        this.name = name;
        this.lang = lang;
        this.address = address;
        this.id = id;
        this.name = name;
        this.age = age;
        this.lang = lang;
        this.address = address;
        this.id = Math.random();
    }
    getName() {
        return `My name is ${this.name}`;
    }
}
let coder = new Coder('Nayan', 28, 'JavaScript', 'LMP');
// Not possible as name is readOnly
// coder.name = 'Golu'; 

Not sure why is this happening as it is just violating the DRY rule.

2

Answers


  1. That is because any access modifier on variables passed in the constructor compiles to exactly that – a declaration on the class and an assignment inside the constructor.

    class Test {
       constructor(public whatever: string){}
    }
    

    is the same as

    class Test {
       public whatever: string;
       constructor(whatever: string) {
          this.whatever = whatever;
       }
    }
    

    so if you write

    class Test {
       constructor(public whatever: string){
          this.whatever = whatever;
       }
    }
    

    it would be equivalent to

    class Test {
       public whatever: string;
       constructor(whatever: string) {
          this.whatever = whatever; 
          this.whatever = whatever;
       }
    }
    
    Login or Signup to reply.
  2. When using modifiers you don’t need to explicitly map the variable yourself, it’s your own code that is the reason for the duplicate. Remove this when using access modifiers:

    this.name = name;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search