I am building an Angular4 project and using IntelliJ. Whenever I create a new class, and then add getters and setters. The IDE adds underscores to the fields.
Being that typescript syntax seems to be recognised automatically by the IDE and yet creates the fields in this way, leaves me to think that this is a best practice, but I have also read that this should not be done.
Why does the IDE do this? And should I allow it to do this for an angular project? Thanks for any help!
Before creating the getters and setters
export class Test { hello:string; world:string; }
After creating the getters and setters
export class Test { private _hello:string; private _world:string; get hello(): string { return this._hello; } set hello(value: string) { this._hello = value; } get world(): string { return this._world; } set world(value: string) { this._world = value; } }
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.
The underscore in variable names is completely optional. Many programmers use it to differentiate private variables - so instance variables will typically have an underscore prepended to the name. This prevents confusion with local variables.
A single leading underscore in front of a variable, a function, or a method name means that these objects are used internally. This is more of a syntax hint to the programmer and is not enforced by the Python interpreter which means that these objects can still be accessed in one way on another from another script.
Since JS and therefore TS lacks runtime encapsulation, an underscore usually signifies internal/private/encapsulated property/variable.
The getter/setter cannot have the name that matches the property name - the following won't work:
class A { get world() { return this.world; } }
So the general pattern is to name the internal properties just like a setter/getter only with the edition of an underscore:
class A { get world() { return this._world; } }
Since JS and therefore TS lacks runtime encapsulation, an underscore usually signifies internal/private/encapsulated property/variable.
But nothing forces you to use underscores. If you name your getter/setter differently, you can avoid adding underscores:
class A { get getWorld() { return this.world; } }
You can specify a different prefix to be used for fields in Settings | Editor | Code Style | TypeScript | Code Generation
, Naming conventions/Field prefix
. But note that leaving the prefix empty will result in TS2300:Duplicate identifier
errors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With