Typescript : underscore convention for members
Just name your private variables as you want but don't use _
. You could create your own standard and stick to it.
Setters and getters are like any other functions so you can follow the method naming convention.
Do not use "_" as a prefix for private properties.
Use whole words in names when possible.
This is a subjective opinion, feel free to use
_
if you must.
Edit:
$
can be used to prefix variable names. In my everyday use case I use it in prefixing observable (rxJS) variables.
Edit:
In the case where you have getters then you can use _
to name the field to avoid name conflict.
Using underscores as a prefix or suffix in variable names at all is generally not regarded as good practice.
See the Google Typescript Style Guide. This guide is intended as a prescriptive guide on style, unlike the Microsoft Style Guide linked in another answer which is primarily intended for contributors to the TypeScript repository.
_ prefix/suffix: Identifiers must not use _ as a prefix or suffix
https://google.github.io/styleguide/tsguide.html
Underscore "_" prefix for private fields is out-of-date style. It's better to name your variable in a readable and friendly way.
See Microsoft Typescript coding convention here
- Do not use "_" as a prefix for private properties.
Those who say, must not use the "_", for them, here is some code from TypeScript site:
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
this._fullName = ......
}
Same question on Stackoverflow, you should have a look on it, especially the answer.
For the time being, if accepted, we should not use _, then what are other better ways?
Let's take your example of email, if we will not use _ then, we will come something like this:
member: to, get/set: emailTo
member: from get/set: emailFrom
might be you can think some better name, but every time you need to think, which is not very common in the developer world!
Using _ and the same name for a property is easy to check the code otherwise we will be keep mapping which property to which member.
BUT: If you have been forced by your lead at your company then you can use $
for member and property without it; not a rule but easy way:
class Employee {
private fullName$: string;
get fullName(): string {
return this.fullName$;
}
this.fullName$ = ......
}
The Choice Is Yours!!!