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
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.
is the same as
so if you write
it would be equivalent to
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: