Thanks for your question :clap:, if someone gives you an answer it would be great if you thanked them with a :white_check_mark: in response. This response will earn you both points for special roles on this server.
#TypeScript Devs: How do you name your private class fields?
3 messages · Page 1 of 1 (latest)
Ctrl+C, Ctrl+V; // @ebon plinth mastering the basics as <@&1244333098284351518>!
Option 2 — Underscore prefix is my preference, and here's why:
private _aspectRatio: number;
get aspectRatio(): number { return this._aspectRatio; }
Pragmatic reasons:
-
It's the de facto TypeScript/Angular/most-major-frameworks convention. Developers immediately recognize
_fooas "backing field forfoo." Zero cognitive overhead. -
Debugging is straightforward. Unlike
#privateField, underscore fields show up normally in console, debugger watches, and stack traces. -
Refactoring tools handle it well. IDE support is mature and predictable.
-
The pattern is self-documenting. When you see
_widthandwidth, the relationship is obvious. WithwidthValue/widthorstoredWidth/width, you have to think about it.
On your other options:
-
#fields: I agree with you—painful in debugging, and the "hard private" guarantee rarely matters in application code. It's solving a problem most TS projects don't have.
-
"Value" suffix: Creates awkward names like
aspectRatioValue. Also, what happens when the getter transforms the value? The name becomes misleading. -
Descriptive names:
zoomLevelvszoomworks here, but it doesn't scale. You'll eventually hit cases where there's no natural semantic distinction, and then you're inventing names for the sake of naming.
The "ugly Java" thing: The underscore convention actually predates Java's popularity and comes from C/C++. Java conventionally doesn't use underscores (hence the this.foo = foo constructor pattern). TypeScript inherited this from C# and earlier JS patterns.