Encapsulating constructor variables in TypeScript classes through private access modifiers and using public getters

Coming from a background in C#, I am used to designing most of my classes to be immutable. I am curious about whether it is considered good practice in TypeScript to use private constructor variables and public getters for accessing data within classes.

Take this example:

class UnitType {
   constructor(private code: string, private name: string, private unitType: string) {

}

get Code(): string {
    return this.code;
}
get Name(): string {
    return this.name;
}
get UnitType(): string
    return this.unitType;
}

I have not been able to find many examples of TypeScript code structured like the one above. Is there something that I am overlooking?

Answer №1

Indeed, practicing encapsulation is highly beneficial. It helps reduce potential errors and simplifies the mental workload for programmers by limiting the scope of variables that need to be managed.

While it is possible to simulate private properties in ES5, it often leads to complex and less readable code. This can also impact performance negatively. Therefore, it is uncommon to come across such implementations in JavaScript due to the absence of built-in private modifiers.

It is important to note that in TypeScript, properties marked as private are only enforced at compile-time. At runtime, when the code is executed as JavaScript, these "private" properties remain accessible despite their designation.

Answer №2

If you want to streamline your class, simply use the public readonly keyword like this:

class UnitType {
    constructor(
        public readonly code: string, 
        public readonly name: string, 
        public readonly unitType: string) {
    }
}

// Example:
var type1 = new UnitType("a", "b", "c");

// This will result in an error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property.
type1.code = "aa";

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 correct method for handling arrays with overlapping types and narrowing them down again

When working with arrays containing different types in TypeScript, I often encounter issues with properties that are not present on all types. The same challenge arises when dealing with various sections on a page, different user roles with varying proper ...

How can one point to a parameter within the documentation of a TypeScript function?

I am attempting to incorporate parameter references in function descriptions like this: /** * Deletes the Travel Cost with the given {@param id} * @param id the id of the travel cost to be deleted */ deleteTravelCost(id: number): Observable<{}> { ...

The tsconfig within the module directory fails to supersede the extended tsconfig properties present in the parent directory

Within the directory store/aisle/fruits, there is a tsconfig.json file: { "compileOnSave": true, "compilerOptions": { . . "target": "es6", "noEmitOnError" : true, "noEmitHelpers ...

Avoiding an event from spreading in Angular

I am working on a navigation setup that looks like this: <a (click)="onCustomParameters()"> <app-custom-start-card></app-custom-start-card> </a> When the user clicks on the app-custom-start-card, the onCustomParame ...

How can I show distinct values in the Angular Material dropdown menu?

I am currently working on implementing a feature where I need to show unique options for the select using angular material. Below is what I have so far: where appitem is an array of items. <mat-form-field> <mat-select placeholder="Select app ...

Angular reference numbers vs ngModel

When is it necessary to use [(ngModel)] on an input, and when can I simply use #reference? For instance: <div class="form-group"> <div class="input-group mb-2"> <input type="text" class="form-control" [(ngModel)]="newUser"> < ...

Instructions on how to dynamically show specific text within a reusable component by utilizing React and JavaScript

My goal is to conditionally display text in a reusable component using React and JavaScript. I have a Bar component that I use in multiple other components. In one particular ParentComponent, the requirement is to show limit/total instead of percentage va ...

Enhancing the design of the Mat Calendar with a stylish border

I've been attempting to put a border around my mat calendar, but I'm having trouble figuring out the specific class that will give me the exact look I want. I need it to be just like this: https://i.sstatic.net/fTGbp.png I tried using the follow ...

Tips for dynamically altering the data type of an object in Angular depending on a certain condition

I'm currently in the process of developing an online store and facing challenges with integrating a dynamic form system that can adapt based on the type of product being added to the store. For instance, if I select the 'Clothing' category, ...

How to verify if an unknown-type variable in TypeScript contains a specific property

When using typescript with relay, the props passed down are of type unknown. Despite my efforts, I am unable to persuade the compiler that it can have some properties without encountering an error: <QueryRenderer environment={environment} query={te ...

Angular 2 and 4 now have a specialized node module designed to create tree-like structures within the framework

Are there any node packages available for creating tree-like structures in Angular 2 or 4, similar to what is shown here ? I am looking for the ability to customize templates within the tree. Any suggestions? ...

Examining the ngOnChanges function of a child component within an Angular unit test

I am currently working on writing unit tests for an Angular child component that uses ngOnChanges with @Input. I found a helpful approach in this article: here Below is a snippet of my code. import { Component, NO_ERRORS_SCHEMA, SimpleChange } from ' ...

Incorporating a new attribute into the JQueryStatic interface

I am trying to enhance the JQueryStatic interface by adding a new property called someString, which I intend to access using $.someString. Within my index.ts file, I have defined the following code: interface JQueryStatic { someString: string; } $.s ...

Angular 10 carousel malfunction: unable to scroll images as intended

Recently, I attempted to integrate a bootstrap carousel into my angular web page. I copied the source code directly from the bootstrap site, so I assumed everything was configured correctly... Despite this, the carousel does not slide as expected. Additio ...

Error in DraftJS: The parameter 'htmlConverter' does not match the expected type 'ContentState'

Utilizing the convertFromHTML function from draft-convert library, I transform my HTML string into an object that can be used as a parameter in EditorState.createWithContent from the draftjs package (as outlined in the README file). However, when attempti ...

Tips for displaying only a single list item at a time using ngFor in Angular

Here is the situation: I have a code snippet that includes an icon within an anchor tag. Upon clicking the icon, a list with li tags is displayed. The issue arises when using ngFor. For example, if i=2, the li is created twice; for i=3, it is created thr ...

callbacks in amazon-cognito-identity-js

When working with amazon-cognito-identity-js, I encountered an issue with the callback function. This is what it currently looks like: cognitoUser?.getUserAttributes((err, results) => { if (err) { console.log(err.message || JSON.stringify(err)); ...

Slider in Angular Material not moving along the track

When I attempt to slide the mat-slider control using the mouse, it doesn't move left or right. Instead, it only responds when I click on a specific point along the sliding line. Here is the code snippet I am using: <div> <mat-slider>& ...

Issue with Dates in Typescript array elements

When attempting to compare different Date elements in my code, I encountered an issue. I have two date elements representing date formats but am unable to compare them because I keep receiving the error message "core.js:6237 ERROR TypeError: newticketList. ...

Swap out the traditional for loop with a LINQ query utilizing the any method

In my TypeScript code, I have the following snippet: public executeTest(test: Test): void { const testFilters: Record<string> = getTestFilters(); let isTestingRequired: boolean = false; for (let i: number = 0; i < testFilters.leng ...