The underscore convention for defining members in Typescript allows for clear and concise

Let's talk about a class called Email

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

When an email object is created, it will look something like this:

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

I find it strange that I can't directly use this object to send to a function. It seems like I'll need to transform the object so that it doesn't have underscores. Do I really have to do this or is there a way to use the underscore convention as is?

EDIT: Removing the _

If we name the private variables without underscore, how should we name the getters and setters? A VSCode plugin called Typescript toolbox suggests using something like this:

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

Is using $ as a prefix for getters a good convention?

Answer №1

In discussions about naming conventions, some argue against using the "_" character. Here is an example code snippet from the TypeScript site to illustrate this:

class Employee {
    private _fullName: string;

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

A similar question can be found on Stackoverflow, where you may find some helpful insights.

If we refrain from using _, what alternative naming schemes could be more effective?

For instance, consider the case of an email property. Without _, the naming convention might look like this:

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

You might suggest better names, but constantly having to rethink these decisions can be cumbersome for developers.

While using _ can simplify code readability by directly linking properties and members, avoiding it means maintaining a mapping between the two.

However: If your company mandates no use of _, consider using $ as a substitute for both member and property names:

class Employee {
    private fullName$: string;

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

The ultimate decision rests with you!

Answer №2

Avoid using "_" as a prefix for private fields, as it is considered an outdated style. It is recommended to choose variable names that are clear and easily understandable.

For more information on coding conventions, refer to the Microsoft TypeScript coding guidelines here

  1. Do not use "_" as a prefix for private properties.

Answer №3

Feel free to choose your own names for private variables without relying on _. You have the freedom to establish and adhere to your own naming standards.

Remember, setters and getters are considered regular functions, so it is important to maintain consistency in method naming conventions.

Avoid using ""_" as a prefix for private properties.
Whenever possible, use complete words in variable names.

Note that this recommendation is subjective, and you have the flexibility to include _ if necessary.

Additional tip: Consider using $ as a prefix for variable names, especially when dealing with observables (like rxJS) in your daily coding tasks.

Edit:

If you encounter conflicts with getter functions, incorporating _ into field names can help mitigate potential issues.

Answer №4

Avoid using underscores as a prefix or suffix in variable names, as this practice is generally considered suboptimal.

For more information, refer to the Google Typescript Style Guide. Unlike the Microsoft Style Guide mentioned in another response, this guide offers specific recommendations on coding style.

_ prefix/suffix: Identifiers should not start or end with _

Visit for further details.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The FlatList glides effortlessly in any direction

My FlatList allows me to drag and move it in all directions (up/down/right/left) even though it appears vertically due to styling. The scroll bar still shows horizontally, which I want to disable. How can I achieve this? This is the code snippet for using ...

Exploring jasmine-node: unraveling the mysteries of errors

As I embark on my journey to learn JavaScript, I decided to tackle some exercises on exercism.io. This platform provides pre-written tests that need to be passed. While things were going smoothly initially, I hit a roadblock with the latest exercise where ...

"Exploring the World of Android WebView with JavaScript

My app has a minimum API of 16, and I need to run some javascript on a web view. However, when I try to use mWebView.evaluateJavascript("(function()...)"); I receive a compile error indicating that this feature is only available in API 19 and higher. Ho ...

Tips for populating a dictionary with a large datalist of around 2000 items

Currently, I'm facing an issue where the code I'm using takes about 10 seconds to run on Chrome and around 2 minutes on IE11, which is the primary browser it will be used with. for (var key in dict) { if (dict.hasOwnProperty(key)) { ...

The React axios request triggers the UseEffect cleanup function to terminate all subscriptions and asynchronous tasks

I'm currently retrieving data from my API using axios, but the requests are not inside a useEffect function. In fact, I haven't used useEffect at all. Here's a snippet of my code: JSX: <form onSubmit={onSubmitLogin}> <div c ...

The settimeout function does not seem to function properly within the context of

Currently, I am facing an issue with implementing block UI for blocking a specific div when a button is clicked. The problem I am encountering is that even though I want the blocked div to be unblocked after a certain delay, it remains permanently blocked ...

How can we ensure that material-ui fields render properly following a reset call in react-hook-form?

I am currently working on a page for editing, but I have encountered an issue with react MUI not rendering text fields properly after updating my form data using the reset method from react-hook-form. This is the current appearance of the form: When I cl ...

Is there a way to eliminate spaces from a string using react-native?

As a user of react-native, I've encountered an issue with inconsistent line breaks when inputting long strings on the screen. For example: I aim to achieve consistent string wrapping as shown in the image below: Here is my code. How can I address t ...

Combining React state value with an HTML tag would be a great way

I am facing an issue while trying to concatenate the previous value with new data fetched from an API using a loop. Instead of getting the desired output, I see something like this: [object Object][object Object],[object Object][object Object] Here is ...

Invoking a PHP class through an AJAX response handler code

I'm attempting to access a PHP-File using AJAX. When I use a basic PHP-File like this: <?php header('Content-Type: text/html; charset=utf-8'); header('Cache-Control: must-revalidate, pre-check=0, no-store, no-cache, max-age=0, pos ...

Is there a way to create a customized calendar in Node.js?

I am looking for a way to showcase a calendar in a localized format, not only in terms of language but also supporting non-Gregorian calendars such as Persian, Chinese, or Buddhist. In the past, when I worked with Java, I relied on ICU4J for this task. Ho ...

Angular 2 Issue: Error Message "Cannot bind to 'ngModel'" arises after FormsModule is added to app.module

I've been struggling with the data binding aspect of this tutorial for over a day now. Here's the link to the tutorial: https://angular.io/docs/ts/latest/tutorial/toh-pt1.html The error I keep encountering is: Unhandled Promise rejection: Tem ...

Converting an ISO date to a standard JS date: The straightforward approach

Can anyone help me with converting an ISO date to a Standard JS Date format? The specific format I need is: Mon `Jul 20 2020 14:29:52 GMT-0500 (Central Daylight Time)` I would appreciate any guidance on the best approach for achieving this. Thank you in a ...

Encountering difficulty when trying to define the onComplete function in Conf.ts. A type error is occurring, stating that '(passed: any) => void' is not compatible with type '() => void'.ts(2322)'

I have been developing a custom Protractor - browserstack framework from the ground up. While implementing the onComplete function as outlined on the official site in conf.ts - // Code snippet to update test status on BrowserStack based on test assertion ...

When a tooltip inside a button is clicked, the hover effect is passing through to the surrounding parent element

I am facing an issue with a nested tooltip within a button. The problem arises when I try to click on the 'read more' link inside the tooltip popup, intending to go to an article. However, instead of redirecting me to the article, clicking on the ...

Is there a way to send map data using props in React?

I just want to store and pass the current props.url to the videomodal so I can show the same active video on the video modal. I can't use useState in the map. How can I pass it? Or is there any other solution? Videos.tsx ( props.url must be in the &l ...

Working with scrollIntoView in useEffect (Encountering an error trying to access 'scrollIntoView' property of null)

Starting from scratch, I'm working on setting up my webpage and crafting some code. function BasicDetails() { React.useEffect(()=>{ scrollView(); }, []); function scrollView() { document.getElementById('main-root& ...

Enhance ant design modal functionality by enabling resizing capabilities

I'm experiencing an issue with the Ant Design Modal component as it does not support resizing the modal window. I'm looking for a way to enable manual resizing of the modal window once it has been opened. Is there a solution available for this fu ...

Looking to update the background color of a div every 3 seconds?

Every 3 seconds, I need to change the background color of each div. To do this, I attempted to modify the values in the color array every 3 seconds. For example, the value at index 0 (which is "red") would move to index 1, then the value at index 1 would ...

Setting the content-type for static assets in NuxtJS

I'm trying to use the Nuxt built-in server to serve the static file /.well-known/apple-app-site-association with a content-type of application/json. Unfortunately, because the file does not have a .json extension, it is returning as application/octet- ...