Exporting constants using abstract classes in TypeScript files

In my Typescript files, I've been exporting constant variables like this:

export const VALIDATION = {
  AMOUNT_MAX_VALUE: 100_000_000,
  AMOUNT_MIN_VALUE: 0,
  DESCRIPTION_MAX_LENGTH: 50,
};

My constant files only contain this one export without any accompanying class. Recently, a colleague suggested that it might be better to export these same constants using an abstract class like this:

export abstract class VALIDATION {
  public static readonly AMOUNT_MAX_VALUE = 100_000_000;
  public static readonly AMOUNT_MIN_VALUE = 0;
  public static readonly DESCRIPTION_MAX_LENGTH = 50;
};

The reasoning behind this suggestion is that it allows developers to easily see the values of the constant variables within VSCode.

Initially, I find this pattern of using an abstract class for exporting constant values unusual, and I haven't come across any resources discussing this approach elsewhere.

Would using an abstract class to export constant values result in any negative impact on the application during build or runtime?

Answer №1

Both options allow you to view the values, but in the first scenario, you have the ability to edit them.

export const VALIDATION = {
  AMOUNT_MAX_VALUE: 100_000_000,
  AMOUNT_MIN_VALUE: 0,
  DESCRIPTION_MAX_LENGTH: 50,
};

VALIDATION.AMOUNT_MIN_VALUE = 5; // This will work

On the other hand, when using a class with readonly flags, editing becomes restricted.

An alternative approach would be to utilize an enum.

export enum VALIDATION {
    AMOUNT_MAX_VALUE = 100_000_000,
    AMOUNT_MIN_VALUE = 0,
    DESCRIPTION_MAX_LENGTH = 50,
};

By using an object instead of a class, there can be some performance improvements.

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

An issue has occurred: The function _co.deleteConsulta is not recognized as a valid function

While following a tutorial on creating a CRUD application using Firestore, I encountered an issue when trying to delete data from Firestore. Every time I attempt to delete a user from my Firestore database, I receive an error stating that ._co.deleteConsul ...

Obtaining Input Field Value in Angular Using Code

How can I pass input values to a function in order to trigger an alert? Check out the HTML code below: <div class="container p-5 "> <input #titleInput *ngIf="isClicked" type="text" class="col-4"><br& ...

Adjusting the transparency of TabBadge in Ionic 2

I am currently working on a project that involves tabs, and I'm looking to update the style of the badge when the value is 0. Unfortunately, I am unsure how to dynamically change the style of my tabs or adjust the opacity of the badge in the style. M ...

Angular ReactiveForms not receiving real-time updates on dynamic values

I'm using reactive forms in Angular and I have a FormArray that retrieves all the values except for product_total. <tbody formArrayName="products"> <tr *ngFor="let phone of productForms.controls; let i=index" [formGroupName]="i"> ...

How to implement a material chiplist in Angular 8 using formGroup

Struggling to include a chip list of Angular material within an Ng form? Unable to add a new chip list upon button click and uncertain about displaying the value of the array added in the new chip list. Take a look at this example: https://stackblitz.com/e ...

Facing problem with Angular 7 when making a GET request for non-JSON data

Currently, I am retrieving JSON data from a URL using the following method: this.http.get('http://localhost:3200/mydata').subscribe(data => { console.log(data); }); The response is in JSON format, and everything seems to be working fine. ...

Using Pydantic to define models with both fixed and additional fields based on a Dict[str, OtherModel], mirroring the TypeScript [key: string] approach

Referencing a similar question, the objective is to construct a TypeScript interface that resembles the following: interface ExpandedModel { fixed: number; [key: string]: OtherModel; } However, it is necessary to validate the OtherModel, so using the ...

Display or conceal elements within a Component with the help of a Service

After developing a custom Tabs component, I have implemented it in the following way (StackBlitz example): <tabs> <tab title="Tab 1"> <div toolbar> <message><span>Message 1: </span></message> &l ...

Create the HTTP POST request body using an object in readiness for submission

When sending the body of an http post request in Angular, I typically use the following approach: let requestBody: String = ""; //dataObject is the object containing form values to send for (let key in dataObject) { if (dataObject[key]) { ...

Top method for transforming an array into an object

What is the optimal method for transforming the following array using JavaScript: const items = [ { name: "Leon", url: "../poeple" }, { name: "Bmw", url: "../car" } ]; into this object structure: const result = ...

The validation using regex is unsuccessful when the 6th character is entered

My attempt at validating URLs is encountering a problem. It consistently fails after the input reaches the 6th letter. Even when I type in "www.google.com," which is listed as a valid URL, it still fails to pass the validation. For example: w ww www ww ...

Implementing the ternary operator on a nested object field in typescript to enforce type validation

Is there an issue with my code or is this intentional? I want to write something similar to this. type MyDefinition = { salutation: string; value?: { typeOfValue: string; val?: string }; }; function create(name: string, input?: Partial<MyDefin ...

Error: Unable to access the 'myDate' property as it is not defined

I've been working on a simple code, but I keep encountering a browser error. The expressjs logs also show an error message. TypeError: Cannot read property 'myDate' of undefined at getReportTable (XXX\dist\controllers&bsol ...

Prevent coverage tracking for files or paths enclosed in square brackets in jest

I am trying to exclude a specific file from test coverage in Jest by modifying the collectCoverageFrom array. The file name contains square brackets, and I have added an entry with a negation for this file. collectCoverageFrom: [ './src/**/*.{js ...

What is the correct way to extract results from an Array of Objects in Typescript after parsing a JSON string into a JSON object? I need help troubleshooting my code

Here is my code for extracting data from an array of objects after converting it from a JSON string to a JSON object. export class FourColumnResults { constructor(private column1: string, private column2: string, private column3: string, priv ...

Encountering the error message "Expected undefined to be truthy" while testing the creation of a Component

Recently, I've been tasked with enhancing my skill set by writing Jasmine/Karma tests for an Angular 9 application. After completing an online tutorial and doing some research via Google, I began working on my initial test cases independently. However ...

In the Angular Google Maps API, is it possible to update the attributes of <agm-marker> directly within the TypeScript code?

Currently, I am fetching markers from the database and displaying them on a map using Angular Google Maps (AGM) by utilizing the <agm-marker> tag. In my code snippet below, you can see how I fetch and store the markers in an array named markers in t ...

Tips for making a property non-nullable in Typescript

The Node built-in IncomingMessage type from DefinitelyTyped's definition (used as req in the (req, res, next) arguments) has specified that url can be nullable. This excerpt shows part of the definition: // @types/node/index.d.ts declare module "http ...

Leverage the generic parameter type inferred from one function to dynamically type other functions

I am in the process of developing an API for displaying a schema graph. Here is a simplified version of what it entails: interface Node { name: string; } type NodeNames<T extends Node[]> = T[number]["name"]; // Union of all node names as strings ...

Ways to retrieve and bind data using onMounted in VueJS

Loading Data in Test.vue Component <template> <li v-for="item in masterCompany" v-bind:key="item.id"> {{ item.displayName }} </li> </template> <script> import Test from "../hooks/Test.hook" ...