Typescript : underscore convention for members

Jeson Dias picture Jeson Dias · Dec 11, 2017 · Viewed 25.5k times · Source

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 ?

Answer

codejockie picture codejockie · Dec 11, 2017

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 to name.

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.