Conventions for Encapsulating Private Properties in Typescript

Query: What is the ideal approach for naming private properties in Typescript and should one always create getters and setters for those properties?

After perusing this link, I found myself reconsidering what I previously thought to be a good coding practice in Typescript: https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines

While I acknowledge that these guidelines are not absolute rules, the suggested convention for naming private properties raises concerns regarding proper encapsulation and utilization of private properties in Typescript. I have been accustomed to prefixing private properties with an underscore and creating corresponding getters and setters to access or modify the value of that property. This convention, reminiscent of Anders' Delphi days, helped distinguish it as a property rather than just another variable, enhancing tooling support.

For instance:

...
private _progress: IImportInfo[];
...
get progress(): IImportInfo[] {
  return this._progress;
}

set progress(value: IImportInfo[]) {
  this._progress = value;
}
...

These values can then be accessed in an html file like so:

<li *ngFor="let item of progress">

Although direct access to the private variable from external sources is possible, it compromises the expected encapsulation benefits typically associated with private variables. Despite this, adhering to encapsulation principles still holds value (in my opinion). However, the purpose of raising this question is not solely based on personal views. Instead, I am seeking insights from experienced angular/typescript developers on best practices for handling Typescript private properties. Even better would be a credible source or website outlining recommended practices for managing private properties.

Appreciate any assistance provided on this matter.

Answer №1

Finally uncovered the solution I had been seeking:

https://vuejs.org/guide/style-guide.html

Attributes and functions Style Rule 05-06 Always use lower camel casing for attributes and methods.

Avoid adding underscores to private attributes and methods.

Why? Aligns with standard naming conventions for attributes and methods.

Why? JavaScript does not have true private properties or methods.

Why? TypeScript development tools offer clear differentiation between public and private attributes and methods.

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

Why ngIf in Angular Ionic doesn't correctly compare arrays from parent when using the 'includes' method?

I have implemented a feature where users can select their interests through a dialog. When a user clicks on a chip, the following method is triggered: handleClick(tag){ let found = false; let index = -1; // tslint:disable-next-line:prefer-for-of for (let ...

Implementing basic authentication with AWS Lambda and Application Load Balancer

A few days ago, I sought assistance on implementing basic-authentication with AWS Lambda without a custom authorizer on Stack Overflow. After receiving an adequate solution and successfully incorporating the custom authorizer, I am faced with a similar cha ...

Check out the uploaded file preview on React Native Expo!

I'm attempting to display a preview of the file uploaded by the user, which could be in pdf, img, or doc format. I tried a method that previews the file using a specific URL, but what I really want is for it to only show the preview of the uploaded fi ...

Angular 14: A collection and schematic must be provided for execution to proceed with the process

I've recently started learning angular. After installing the latest version, I created an app called "test" using the command ng new test. Next, I opened the app in Visual Studio Code and tried to create a new component by entering the command: ng g ...

Sending selected IDs from the JSON data

In my project, there is a JSON file named "workers" which contains information about all the workers. I have created a select component to display the names of the workers like this: https://i.sstatic.net/0Glyf.png Currently, I am selecting some workers ...

"Ionic Calendar 2 - The ultimate tool for organizing your

I am using a calendar in my Ionic app that retrieves events from a database through an API. var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://portalemme2.com.br/SaoJoseAPI/agenda', true); this.http.get('http://portalemme2.c ...

Tips for widening a union data type in a different section?

Is there a way to expand on a union type from another module? Below is an example showcasing the need for this, but I encountered a ts(3200) error due to duplicate identifiers. The Core module @org/core defines a union type called OptionType: // Defined i ...

Angular and Spring setup not showing data despite enabling Cross Origin Support

I'm currently in the process of developing a full stack application using Spring and Angular. After successfully setting up my REST APIs which are functioning properly on port 8080, I encountered an issue when trying to access them from my frontend ( ...

Converting a generic object from snake_case to camelCase using TypeScript

Looking to create a function that can transform an object with snake case keys into one with camel case keys. How can this be achieved in TypeScript by typing the input object, but keeping the solution generic? type InputType = { snake_case_key_1: numbe ...

What is the best way to save emitted values from rxjs?

I'm currently grappling with understanding rxjs. In my angular project, I've created a service that emits and listens to boolean values that indicate the start and completion of asynchronous operations. export class UpdateScriptRunningEventServi ...

Ways to set a default value for a union type parameter without encountering the error "could be instantiated with a different subtype of constraint"

After referring to my recent inquiry... Can a default value be specified for valueProp in this scenario? type ValueType = 'value' | 'defaultValue' type Props<T extends ValueType> = Record<T, string> ...

Issue with Filtering Function in Kendo Angular 2 Grid

I have recently started incorporating the Kendo Grid with Angular 2 by following the guidelines in this tutorial: http://www.telerik.com/kendo-angular-ui/components/grid/data-binding/. However, I am facing a challenge as I am unable to locate the filteri ...

What is the best way to choose the member variables in this specific data structure?

I have been assigned the task of retrieving the cities from various countries, but I am unsure of the best approach to do so. How can I easily extract city names like: For example, for USA it would be NYC and SFO. I attempted using the code snippet cityD ...

Enhance the functionality of a module by incorporating plugins when Typescript definitions are divided into multiple files

During my exploration of Typescript 2.2, I encountered a challenge in defining a module for HapiJS with various plugin options. To streamline the core code, I split it into multiple .d.ts files and then imported and re-exported them all from the index.d.t ...

Substitute data types for certain keys within a Typescript interface

Within this code snippet, the goal is to create a new type from an existing one by iterating through the keys and only replacing those that meet a specific condition. Additionally, union types are being utilized here. class A {} class B { constructor ...

Accessing HTTP data through a function instead of using ngOnInit in Angular is a more efficient approach

Trying to retrieve data from a service using setInterval has posed an issue for me. When I call the service from ngOnInit, everything functions as expected. However, when attempting to call it from any other function, an error occurs: "ERROR TypeError: Ca ...

Exploring the wonders of mocha in NYC alongside the magic of source

Trying to understand why this approach isn't yielding the desired results. The task involves developing TypeScript code in files located within the src and tests directories. These files are of types *.ts and *.spec.ts. The transpilation of both sou ...

Creating an ngFor loop with an ngIf condition for true and false bot conditions

I am attempting to troubleshoot an issue where if my condition is true, return true. If my condition is false, return false. However, currently, if only one condition is true, all conditions are being applied as true. Please help me resolve this problem. ...

Bringing in Leaflet for Angular 2 and beyond

Hello there! I'm currently diving into the world of Angular 2 and wanting to figure out how to integrate Leafletjs with it. My goal is to set up Leafletjs without having to directly include JS and CSS in my index.html file. Additionally, I want to ens ...

Tips for manipulating 2 arrays where the value in one array is reliant on the value in another array

Currently, I have two arrays - arrayGuest and arrayRent. They both contain objects with a common field, GuestID. My goal is to create a list that combines fields from both arrays when their guestIDs match. The structure of the objects is as follows: class ...