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

The functionality for jest mocking with the Google Secret Manager client is currently not working as

i am currently working on retrieving secrets from GCP Secret Manager using the code snippet below: import { SecretManagerServiceClient } from '@google-cloud/secret-manager'; const getSecrets = async (storeId) => { try { const client = n ...

Utilize Typescript to aim for the most recent edition of EcmaScript

Are you looking to configure your typescript build to compile to the most recent version or the most current stable release of EcmaScript? For example, using this command: tsc --target <get latest version> Alternatively, in a tsconfig file: { & ...

Encountering an error in Angular 4: 'Cannot find property on specified component type'

I recently embarked on the journey of learning Angular 4 and TypeScript, but I've encountered my first obstacle. My current challenge involves creating a simple date and time component. Despite having a seemingly correct Javascript code, I believe I ...

How do I add a new item to an object using Ionic 2?

example item: this.advData = { 'title': this.addAdvS2.value.title , 'breadcrumb': this.suggestData.breadcrumb, 'price': this.addAdvS2.value.price ...

Incorporating a class element within an Angular 2 directive

When working with Angular 2 directives, one way to add an element is by using the following code: this._renderer.createElement(this._el.nativeElement.parentNode, 'div'); After adding the element, how can I set its class and keep a reference to ...

Unlocking 'this' Within a Promise

I seem to have an issue with the 'this' reference in the typescript function provided. It is not correctly resolving to the instance of EmailValidator as expected. How can I fix this so that it points to the correct instance of EmailVaildator, al ...

The debate between using backticks and colons in TypeORM queries

Lately, I've been crafting queries utilizing backticks const firstUser = await connection .getRepository(User) .createQueryBuilder("user") .where(`user.id = '${id}'`) .getOne(); However, in the typeorm documentatio ...

Ways to retrieve data beyond the constructor

Here is the code snippet from my component.ts: export class OrganizationsComponent { public organizations; constructor(public access: OrganizationService) { this.access.getOrganizations().subscribe((data => { this.organizations = data; ...

How can you transform an object literal AST from a TypeScript file into executable code?

Is there a way to convert a JSON or Object Literal file into executable code? const astInJson = {"pos":0,"end":79,"flags":0,"kind":268,"text":"export interface Order {\n\torderId: string;\n\titineraries(id: string): string;\n}&b ...

Using Typescript to Encapsulate the Assertion that Foo Belongs to a Specific Type

For the purpose of this demonstration, let's define two dummy classes and include some example code: class X { constructor() {} } class Y extends X { value: number; constructor(value: number) { super(); this.value = valu ...

Encountering a TypeScript error in MUI 5 when attempting to spread values in props

I am encountering an issue with a typescript error related to the MUI sx prop. The problem arises when I attempt to merge or spread multiple sx values into an sx prop, resulting in an error. It seems to work fine if only one item is present in the sx prop, ...

Create a versatile generic object using TypeScript

Looking to create a versatile onFilterChange helper function that works for all filters, eliminating the need to write it out separately each time. However, I've hit a snag: // helper.ts export function onFilterChange(prevState: Record<string, any& ...

Issue: Vue TypeScript module not foundDescription: When using

Is there anyone out there who can assist me with this issue regarding my tsconfig.json file? { "compilerOptions": { "target": "esnext", "module": "esnext", "moduleResolution": " ...

When a function is transferred from a parent component to a child component's Input() property, losing context is a common issue

I have encountered an issue while passing a function from the parent component to the child component's Input() property. The problem arises when the parent's function is called within the child component, causing the this keyword to refer to th ...

How to format dates with month names in various languages using the date pipe

In my HTML code, I have set up the date display like this: <span >{{ item.lastModified | date : 'MMM d, y' }}</span> As a result, the displayed date looks something like Jul 20, 2021. However, when I switch my browser's language ...

Leveraging Multiple @Input Decorators in Ionic 3 and Angular 2

Within my Ionic 3 project, I have developed a custom component called my-component. Utilizing the angular @Input functionality, data can be passed to this component with ease. In this case, I have two inputs defined as: @Input('finder') myFinder ...

Encountering ReferenceError when attempting to declare a variable in TypeScript from an external file because it is not defined

Below is the typescript file in question: module someModule { declare var servicePort: string; export class someClass{ constructor(){ servicePort = servicePort || ""; //ERROR= 'ReferenceError: servicePort is not defined' } I also attempted t ...

Error in hook order occurs when rendering various components

A discrepancy was encountered in React when attempting to render different components Warning: React has detected a change in the order of Hooks called by GenericDialog. This can result in bugs and errors if left unresolved. Previous render Next ren ...

Rendering a child component in the DOM tree with Aurelia StageComponent

Imagine having an app.html template structured like this: <template> <require from="./MyComponent"></require> <h1>${message}</h1> <my-component>test</my-component> </template> Accompanied by MyCompone ...

How can I retrieve List<T> from a Razor Page using TypeScript?

Within my ViewModel, I have an Items collection: public class ItemViewModel{ public List<Item> Items {get;set;} } In the Index.cshtml file: @if(Model.Items != null){ <li><a id="item-id-link" href="#" data-items="@Model.Items"> ...