How can I retrieve the name of a constant enum member in TypeScript as a string?

Consider the following const enum declaration:

const enum Snack {
    Apple = 0,
    Banana = 1,
    Orange = 2,
    Other = 3
}

Is it possible in TypeScript to retrieve the string representation of a specific member?

In C#, this could be achieved with nameof(Snack.Orange). (While nameof is not available in TypeScript, there are workarounds for non-const enums.)

Answer №1

Const enums are typically removed at compile time, meaning there is no runtime representation of the enum object. To preserve const enums and force the generation of the enum object, you can use preserveConstEnums. However, even with this flag, accessing the enum object directly is not allowed by the compiler, requiring a workaround.

One approach with preserveConstEnums enabled is to place the enum within a namespace:

namespace enums {
    export const enum Snack {
        Apple = 0,
        Banana = 1,
        Orange = 2,
        Other = 3
    }
}
let enumName = (enums as any).Snack[enums.Snack.Apple];

Alternatively, if the enum is part of a module:

export const enum Snack {
    Apple = 0,
    Banana = 1,
    Orange = 2,
    Other = 3
}

let enumName = (exports as any).Snack[Snack.Apple];

If you prefer not to use the flag, another workaround is to create an object that must include all enum members, allowing you to search for the name within it. This way, any additions or removals from the enum will prompt a compile-time error on the object:

let SnackNames: { [P in keyof typeof Snack]: { Name: P, Value: typeof Snack[P] } } = {
    Apple: { Value: Snack.Apple, Name: "Apple" },
    Banana: { Value: Snack.Banana, Name: "Banana" },
    Orange: { Value: Snack.Orange, Name: "Orange" },
    Other: { Value: Snack.Other, Name: "Other" },
}

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

Creating an NPM package using Visual Studio 2017: A Step-by-Step Guide

I enjoy developing and publishing NPM packages using Visual Studio 2017. My preferred method is using TypeScript to generate the JavaScript files. Which project template would be best suited for this particular project? ...

Leverage glob patterns within TypeScript declaration files

Utilizing the file-loader webpack plugin allows for the conversion of media imports into their URLs. For example, in import src from './image.png', the variable src is treated as a string. To inform TypeScript about this behavior, one can create ...

The HTML canvas drawImage method overlays images when the source is modified

Trying to implement a scroll animation on my website, I came across a guide for creating an "Apple-like animation" using image sequences. Even though I'm new to Angular, I attempted to adapt the code to work with Angular. However, instead of animatin ...

What could be the reason for my Angular 2 app initializing twice?

Can someone help me figure out why my app is running the AppComponent code twice? I have a total of 5 files: main.ts: import { bootstrap } from '@angular/platform-browser-dynamic'; import { enableProdMode } from '@angular/core'; impor ...

Tips on leveraging an attribute for type guarding in a TypeScript class with generics

Is there a way to utilize a generic class to determine the type of a conditional type? Here is a basic example and link to TS playground. How can I access this.b and this.a without relying on as or any manual adjustments? type X<T> = T extends true ...

Creating a TypeScript client using NSwag with named properties: A step-by-step guide

Our TypeScript client is created from a swagger interface using NSwag. The resulting client code typically looks like this: client.EndPointFoo(arg1, arg2, arg3, ...) However, we encounter issues when NSwag changes the order of arguments in response to mo ...

Using Angular to access HTML content through the .ts file

Is there a way to retrieve the value of the input field [newUser] when clicking on the button and executing the action [onAddUser()] in the .ts file? <input type="text" ng-model="newUser" style="text-align:center"/> <button (cl ...

What is the best way to see if a variable is present in TypeScript?

I am facing an issue with my code that involves a looping mechanism. Specifically, I need to initialize a variable called 'one' within the loop. In order to achieve this, I first check if the variable exists and only then proceed to initialize it ...

What is GraphQl indicating when it informs me that I neglected to send arguments for the mutation

My GraphQL schema consists of various mutations and queries. I believe that validation of mutations should only occur when I send mutation { ... } to the graphql server. However, currently, the server is informing me that I have not sent arguments for all ...

the undefined 'pipe' cannot be read

Trying to perform unit testing for an Angular component is a new experience for me. Currently, I am encountering a specific issue that I would like assistance with. The component in question contains the following select statement: this.store.select(getI ...

The NextJS API route functions flawlessly when tested locally, generating over 200 records. However, upon deployment to Vercel, the functionality seems to

Here is the API route that I am using: https://i.stack.imgur.com/OXaEx.png Below is the code snippet: import type { NextApiRequest, NextApiResponse } from "next"; import axios from "axios"; import prisma from "../../../lib/prisma ...

NGXS: Issue with passing objects to "setState" occurs when any of the patched inner fields is nullable or undefined

In my Angular components, I have created a class that is responsible for storing the state: export class MyStateModel { subState1: SubStateModel1; substate2: SubStateModel2; } This class has simple subclasses: export class SubStateModel1 { someField ...

The identifier 'name' is not found in the specified data type

How can I resolve the error 'Property 'name' does not exist on type' in TypeScript? Here is the code block : **Environment.prod.ts** export const environment = { production: true, name:"(Production)", apiUrl: 'https://tes ...

Typescript is throwing an error stating that the type 'Promise<void>' cannot be assigned to the type 'void | Destructor'

The text editor is displaying the following message: Error: Type 'Promise' is not compatible with type 'void | Destructor'. This error occurs when calling checkUserLoggedIn() within the useEffect hook. To resolve this, I tried defin ...

The Jest test is experiencing a failure as a result of an imported service from a .ts file

In my Jest test file with a .spec.js extension, I am importing an index.js file that I need to test. Here is the code snippet from the .spec.js file: var HttpService = require('./index.js').HttpService; The problem arises because the index.js f ...

Modify the database entry only if the user manually changes it, or temporarily pause specific subscriptions if the value is altered programmatically

After a change in the viewmodel, I want to immediately update the value on the server. class OrderLine { itemCode: KnockoutObservable<string>; itemName: KnockoutObservable<string>; constructor(code: string, name: string) { ...

What is the best way to insert an item into a tree structure when determining the appropriate level for insertion is necessary beforehand?

Currently, I am dealing with a tree-like object structure: interface Node { id: number; name: string; children?: Node[]; } NODE_DATA: Node[] = [ { id: 1, name: 'A' }, { id: 2, name: 'B', children: [ ...

angular displaying incorrect values for counter

Hi there, I am new to using Angular and I'm currently facing an issue with increasing and decreasing product quantity on the cart page. The problem is that in my first index it works fine, but in the second index, the value starts with the first index ...

What steps can be taken to safeguard data while navigating within the Angular framework?

I am facing an issue with storing an array of items in a service (referred to as cart service) and displaying it in the component (cart.component.ts). The components bgview.component.ts and single.component.ts are involved in selecting individual items, wi ...

React with Typescript - cannot be expressed as a function

I am currently exploring ReactJS and Typescript. While trying to authenticate a user using the methods below, I encountered the following error message: Unhandled Rejection (TypeError): auth.authenticate is not a function onSubmit src/components/Login/ind ...