Javascript – Typescript : underscore convention for members

ecmascript-6es6-classjavascripttypescripttypescript2.0

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 ?

Best Answer

Those who say, must not use the "_", for them, here is some code from TypeScript site:

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    } 
    this._fullName = ......
}

Same question on Stackoverflow, you should have a look on it, especially the answer.

For the time being, if accepted, we should not use _, then what are other better ways?

Let's take your example of email, if we will not use _ then, we will come something like this:

member: to,      get/set: emailTo
member: from     get/set: emailFrom 

might be you can think some better name, but every time you need to think, which is not very common in the developer world!

Using _ and the same name for a property is easy to check the code otherwise we will be keep mapping which property to which member.

BUT: If you have been forced by your lead at your company then you can use $ for member and property without it; not a rule but easy way:

class Employee {
    private fullName$: string;

    get fullName(): string {
        return this.fullName$;
    } 
    this.fullName$ = ......
}

The Choice Is Yours!!!