Can you explain the significance of using square brackets in the typescript enum declaration?

While reviewing a typescript file within an Angular ngrx project titled collection.ts, I came across the declaration of enum constants.

import { Action } from '@ngrx/store';
import { Book } from '../models/book';

export enum CollectionActionTypes {
  AddBook = '[Collection] Add Book',
  AddBookSuccess = '[Collection] Add Book Success',
  AddBookFail = '[Collection] Add Book Fail',
  RemoveBook = '[Collection] Remove Book',
  RemoveBookSuccess = '[Collection] Remove Book Success',
  RemoveBookFail = '[Collection] Remove Book Fail',
  Load = '[Collection] Load',
  LoadSuccess = '[Collection] Load Success',
  LoadFail = '[Collection] Load Fail',
}

/**
 * Actions for Adding Books to Collection
 */
export class AddBook implements Action {
  readonly type = CollectionActionTypes.AddBook;

  constructor(public payload: Book) {}
}

...

export type CollectionActions =
  | AddBook
  | AddBookSuccess
  ...
  | LoadFail;

It seems that providing values to enum constants is standard practice, but there's confusion about the significance of [Collection] attached to each constant. Does this extra notation affect the value or convey something else? Any insights on this concept would be greatly appreciated.

Answer №1

Perhaps you are utilizing a flux/redux framework such as ngrx store or something similar. This enumeration defines actions and guarantees that your action keys (which are strings) are distinct on a universal level because ultimately, they all come together into one extensive set of actions that reducers respond to. To maintain this requirement, it is common practice to prefix the type that the actions belong to at the start of the key within square brackets. This is simply a naming convention unrelated to typescript.

For instance,

Let's say you have entities named Book and Category. Both of them could have an action with the key Load Entity. To differentiate between these two action keys, one approach is to include identifiers like [Book] Load Entity and [Category] Load Entity.

Answer №2

The symbols enclosed within the value string do not hold any inherent significance in the context of the enum or TypeScript. In this particular project, the usage of brackets is merely a customary practice - they could easily be replaced by parentheses or braces without affecting the functionality. These symbols may or may not serve another purpose.

You might be reminded of a similar syntax involving computed keys, such as:

const propNam = 'test';
const obj = {[propName]: 2};
console.log(obj.test); // 2

However, such constructions are not permitted in enum declarations. The compiled JavaScript code resulting from an enum declaration does employ computed keys for reverse mappings, as elaborated on in this page:

TypeScript:

enum Enum {
    A
}
let a = Enum.A;
let nameOfA = Enum[a]; // "A"

JavaScript:

var Enum;
(function (Enum) {
    Enum[Enum["A"] = 0] = "A";
})(Enum || (Enum = {}));
var a = Enum.A;
var nameOfA = Enum[a]; // "A"

It's important to note that this concept differs significantly from the use of brackets in your scenario.

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

Invoke an RxJs observable to handle errors and retry the process

I have an observable called submit$ that submits a form. If this observable encounters an error with status code 403, it means the user is not authorized and needs to log in first. Is there a way to automatically trigger another observable when a specific ...

Try querying again if you receive no results from an http.get request in Angular using RXJS Operators

In my Angular service, I sometimes encounter an issue where I receive an empty array. In such cases, I would like to trigger a fresh query. let request = this.http.post(this.searchlUrl, payload).pipe( retryWhen(errors => errors.pipe(delay(100 ...

Utilize the canActivate method to decide when to display a specific hyperlink

I'm facing a challenge with my AuthGuard implementation using CanActivate to decide whether or not to display a link. Despite my efforts, I am unable to properly check the canActivate property of the Route. Here is the function I created: TypeScript ...

What is the best way to adjust the size of an Angular Material Slider?

I'm attempting to insert a slider into my program, but the slider is displaying as too lengthy for the designated space. I'm curious if there's a straightforward method of adjusting its length to fit better within the container. So far, I&a ...

Frontend receiving data from an unexpected localhost address even with proxy settings in place

My React frontend application has a proxy configured in the package.json file to connect to my Flask backend running on http://localhost:2371. However, when trying to fetch data from the backend using fetch("/members"), the frontend is unexpectedly fetchin ...

Modify the internal class style to set overflow property to visible for a particular class in PrimeNG

Looking for a way to customize the styles of PrimeNG or Angular2 components? The documentation may be lacking clarity, but you can find more information at this URL: http://www.primefaces.org/primeng/#/dialog So, how do you actually go about changing the ...

Angular 2 dropdown list that allows users to add a personalized value in the HTML code

Here is the scenario I am dealing with We are displaying a fixed dropdown list to the user For example, a dropdown list has 4 options such as apple, orange, grape, pineapple and 'create your own' If the user is not satisfied with the provided ...

Jest's it.each method is throwing an error: "This expression is not callable. Type 'String' has no call signatures."

I've been attempting to utilize the describe.eachtable feature with TypeScript, but I keep running into an error message stating: "error TS2349: This expression is not callable. Type 'String' has no call signatures." Below is my code snippe ...

Errors occur with Metro bundler while utilizing module-resolver

Recently, I completed a project using the expo typescript template that runs on both iOS and Android platforms, excluding web. To enhance my development process, I established path aliases in the tsconfig.json file as shown below: "paths": { "@models/ ...

Efficiently process and handle the responses from Promise.all for every API call, then save the retrieved data

Currently, I am passing three API calls to Promise.all. Each API call requires a separate error handler and data storage in its own corresponding object. If I pass test4 to Promise.all, how can I automatically generate its own error and store the data in ...

Changing the color of the pre-selected date in the mat-datepicker Angular component is a key feature that can enhance the

Is there a way to adjust the color of the preselected "today" button in mat-datepicker? https://i.stack.imgur.com/wQ7kO.png ...

Problem with selecting dates in rangepicker

Having trouble with my recursion code for selecting dates in a rangepicker: recurse( () => cy.get('.mantine-DatePicker-yearsListCell').invoke('text'), (n) => { if (!n.includes(year)) { //if year not f ...

The initial click may not gather all the information, but the subsequent click will capture all necessary data

Issue with button logging on second click instead of first, skipping object iteration function. I attempted using promises and async await on functions to solve this issue, but without success. // Button Code const btn = document.querySelector("button") ...

Could routerLinkActive be used to substitute a class rather than simply appending one?

I have a navigation bar icon that links to an admin route. I want this icon to change its appearance when on that specific route. To achieve this, I can simply replace the mdi-settings-outline class with mdi-settings, displaying a filled version of the sam ...

Using Typescript with React functional components: the proper way to invoke a child method from a parent function

My current setup is quite simple: <Page> <Modal> <Form /> </Modal> </Page> All components mentioned are functional components. Within <Modal />, there is a close function defined like this: const close = () => ...

What is the best way to shorten text in Angular?

I am looking to display smaller text on my website. I have considered creating a custom pipe to truncate strings, but in my situation it's not applicable. Here's what I'm dealing with: <p [innerHTML]="aboutUs"></p> Due to t ...

Angular 7: Separate Views for Search Bar and Results

Two components have been developed: search-bar.component.ts: displayed in all views search.component.ts: responsible for displaying the results (response from a REST API) The functionality is as follows: whenever I need to perform a global search (produ ...

`Upkeeping service variable upon route alteration in Angular 2`

Utilizing a UI service to control the styling of elements on my webpage is essential. The members of this service change with each route, determining how the header and page will look. For example: If the headerStyle member of the service is set to dark ...

Creating a new component when a click event occurs in React

Currently diving into the world of React while working on a project that involves mapbox-gl. I'm facing an issue where I can successfully log the coordinates and description to the console upon hover, but I can't seem to get the popup to display ...

Unable to assign a value to an undefined property in TypeScript

I need to store data in an object and then add it to another object let globalSamples = {} as any; let sample = { } as ISamplesDetail []; sample = []; for (let i = 0 ; i<this.prelevementLingette.samplesDetail.length; i++) { sample [i].id= thi ...