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

Include additional information beyond just the user's name, profile picture, and identification number in the NextAuth session

In my Next.js project, I have successfully integrated next-auth and now have access to a JWT token and session object: export const { signIn, signOut, auth } = NextAuth({ ...authConfig, providers: [ CredentialsProvider({ async authorize(crede ...

Exploring Angular 4: Iterating Over Observables to Fetch Data into a Fresh Array

Context Currently, I am in the process of developing a find feature for a chat application. In this setup, each set of messages is identified by an index. The goal of the `find()` function is to retrieve each message collection reference from the `message ...

Angular: finding out if Observable or BehaviorSubject has undergone any important modifications

I am facing an issue with my user object in a membership service. I need to ensure that my services are updated only when there are relevant changes in the user object. To determine if there are relevant changes in the user object, I compare it with the ...

A guide on including a class to a DOM element in Angular 6 without relying on Jquery

Currently, I have created a component template using Bootstrap that looks like this: <div class="container"> <div class="row my-4"> <div class="col-md-12 d-flex justify-content-center"> <h2> ...

What is the most effective way to refresh SCSS in a current Angular project?

I'm in the process of updating the SCSS version within my angular project. From the beginning, I selected scss in the angular cli for this project, so I have been using SCSS already. However, now I need to incorporate a spacing library that requires t ...

Is it possible to use null and Infinity interchangeably in JavaScript?

I've declared a default options object with a max set to Infinity: let RANGE_DEFAULT_OPTIONS: any = { min: 0, max: Infinity }; console.log(RANGE_DEFAULT_OPTIONS); // {min: 0, max: null} Surprisingly, when the RANGE_DEFAULT_OPTIONS object is logged, i ...

The assignment of `accessToken` is restricted in Mapbox-gl's typing

I'm currently utilizing the mapbox-gl library in conjunction with TypeScript. Moreover, I have successfully installed its type definitions that are sourced from the community using @types/mapbox-gl. However, when attempting to import and assign an acc ...

Tips for validating form input upon submission in Angular 6

Within my Angular application, I have successfully implemented form validators. However, I am aiming to trigger form validation specifically upon submission. This means that when the user clicks on the submit button and the form is invalid, the errors indi ...

The datatable only accepts arrays and Iterable data types

While attempting to perform a CRUD operation with the datatable, I encountered an error message "Only arrays and iterables are allowed in datatable" upon clicking the submit button for creation. The console pointed out the error in the component.html file ...

Looking to transform a timestamp such as "2021-07-18T9:33:58.000Z" into a more readable format like 18th July for the date or 9:33 am for the time using Angular?

Is there a way to convert the Timestamp format "2021-07-18T9:33:58.000Z" to display as 18th July (for date) or 9:33 am (for time) in an Angular 11 application? Currently, my code looks like this: const myDate = new DatePipe('en-US').transform ...

The command 'npm cache clean' is failing to work in the Angular environment when using Visual Studio Code as the integrated

npm ERROR! Starting from npm@5, the npm cache will automatically fix any corruption issues and ensure that data extracted from the cache is always valid. To verify consistency, you can use 'npm cache verify' instead. npm ERROR! npm ERROR! ...

The functionality of @Output and custom events appears to be malfunctioning

I am a beginner in Angular and attempting to pass data between child and parent components. In the child component.ts file: @Output() doubleClick = new EventEmitter<string>(); onDoubleClick(nameAccount: string){ this.doubleClick.emit(nameAccoun ...

What is the process for loading the chosen option JSON object from an array when a button is clicked?

I have a TypeScript file containing JSON objects that can be selected as options from a dropdown list. I am looking for guidance on how to load/instantiate the selected JSON object when the user clicks a button to proceed. Specifically, I would like to le ...

Binding data to custom components in Angular allows for a more flexible

In my current scenario, I am looking to pass a portion of a complex object to an Angular component. <app-component [set]="data.set"></app-component> I want the 'data.set' object in the parent class to always mirror the 'set&apo ...

Updating input values in Angular 5 with the currency pipe

Currently, I am utilizing the currency pipe to convert input values in Angular 5. However, I have noticed that it only works after unfocusing the input box. I am seeking a solution where the value is masked as soon as it is entered, similar to the example ...

The error message "angular4: No directive matching with exportAs set to ngModel" is being encountered

Currently encountering an issue with angular 4 Encountering a problem where there is no directive with "exportAs" set to "ngModel" ("" name="fullname" type="text" required maxlength="30" [(ngModel)="model.fullname" [ERROR ->]#full ...

I am trying to figure out how to send a One Signal notification from my Ionic app using the One Signal REST API. I have reviewed the documentation, but I am still unable to understand it

Is there a way to send a one signal notification from my ionic app using the one signal API? I have reviewed the documentation but am having trouble with it. While I have set up the service and it is functional, I can only manually send notifications thr ...

Revitalizing ngFor in Angular 9: Refreshing object properties for re-rendering

I am currently working with an array of objects named Guests: [ {id: 1, first_name: "Tom", last_name: "", logo: 2}, {id: 2, first_name: "John", last_name: "", logo: 3}, {id: 3, first_name: "Jim", l ...

Vercel encountered issues with "validating code quality and type correctness" during deployment but was successful when performed locally

Running "next build" locally and "vercel build" both work smoothly. However, once deployed to vercel, the "Linting and checking validity of types" fails during the build process. It seems like TypeScript is stricter when building on vercel even with the sa ...

Issue in Angular Material: The export 'MaterialComponents' could not be located in './material/material.module'

I'm relatively new to Angular and I am encountering some difficulties when trying to export a material module. The error message that appears is as follows: (Failed to compile.) ./src/app/app.module.ts 17:12-30 "export 'MaterialComponents&ap ...