#TypeScript Devs: How do you name your private class fields?

3 messages · Page 1 of 1 (latest)

jagged minnowBOT
#

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.

#

Ctrl+C, Ctrl+V; // @ebon plinth mastering the basics as <@&1244333098284351518>!

worthy bridge
#

Option 2 — Underscore prefix is my preference, and here's why:

private _aspectRatio: number;
get aspectRatio(): number { return this._aspectRatio; }

Pragmatic reasons:

  1. It's the de facto TypeScript/Angular/most-major-frameworks convention. Developers immediately recognize _foo as "backing field for foo." Zero cognitive overhead.

  2. Debugging is straightforward. Unlike #privateField, underscore fields show up normally in console, debugger watches, and stack traces.

  3. Refactoring tools handle it well. IDE support is mature and predictable.

  4. The pattern is self-documenting. When you see _width and width, the relationship is obvious. With widthValue/width or storedWidth/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: zoomLevel vs zoom works 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.