According to the offical style guide you should
Avoid prefixing private properties and methods with an underscore.
As I come from a Java background, I usually would just use the this
keyword:
export default class Device {
private id: string;
constructor(id: string) {
this.id = id;
}
public get id(): string { // [ts] Duplicate identifier 'id'.
return this.id;
}
public set id(value: string) { // [ts] Duplicate identifier 'id'.
this.id = value;
}
}
But the TypeScript compiler complains: [ts] Duplicate identifier 'id'.
Is there a convention or best practice for parameter naming in a TypeScript constructor?
EDIT
Sorry I missed the essential part of the code which actually causes the TS compiler error.
Using the get and set property of TypeScript produces the error.
So my updated question: Is there a way to follow the style guide and also use the get/set properties of TypeScript?
If the question is strictly :
Where the TypeScript Style Guide says :
Then you can use the
$
(dollar sign) instead of the_
(underscore) to prefix your private fields. In this way you both get rid of the[ts] Duplicate identifier 'blablabla'
error while still respecting the TypeScript Style Guide.In addition, but it is just my opinion, the
.$
combination is more readable than the._
combination.Answer
If you want to use
get
andset
accessors, you have to prefix the private property with underscore. In all other cases don't use it. I would say using underscore with accesors is a special case and although it's not explicitely written in Coding guidelines, it doesn't mean it's wrong. They use it in the official documentation.Reason for the underscore
For start, I would like to emphasize the difference between
field
andproperty
. In standard high level OOP languages like Java or C#, field is a private member which shouldn't be visible to other classes. If you want to expose it with encapsulation in mind, you should create a property.In Java you do it this way (it is called Bean properties):
Then you can access the property by calling these methods:
On the other hand, C# was designed so that it's much easier to use properties:
(value is always the assigned value.)
You can directly assign values to these properties or get the property values.
In plain JavaScript, there are no real fields, because the class members are always public; we simply call them properties.
In TypeScript, you can define "true" C#-like properties (with encapsulation). You use Accessors for that.
Usage:
You have to use underscore here because of two reasons: