javascripttypescriptecmascript-6typescript2.0es6-class

Typescript : underscore convention for members


I have a class Email

class Email {
  private _from: string;
  private _to: Array<string>;
  private _subject: string;
}

It'll create an email object something like:

{
  _from:'',
  _to:'',
  _subject:''
}

This seems a little weird to me since I cannot directly use this object to send to a function . Instead I'll have to transform the object so that it doesn't have underscores . So how do I use the underscore convention or do I have to transform the object .

EDIT : If I do drop the _

How do I name the getters and setters if we name the private variables without underscore? A VSCode plugin called Typescript toolbox creates them something like this

public get $subject(): string { 
  return this.subject;
}

Is $ a good convention ?


Solution

  • 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.