Accessing the name and value of an enum in Typescript

One particular enum is causing some confusion:

export enum myEnum {
  name1 = 'my name',
  name2 = 'my other name',
  name3 = 'other'
}

An object of myEnum has been created:

const x = myEnum.name1;
console.log(x)  // prints 'my name' 

Is there a way to output 'name1' using the variable x? Essentially, how can the enum name 'name1' be retrieved using a myEnum value like 'myEnum.name1'?

UPDATE:

Here is a visual representation:

https://i.sstatic.net/r1Pa6.png

https://i.sstatic.net/FjMKv.png

Answer №1

Referring to the official documentation, enums can be mapped in reverse like this:

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

To list the values and keys of the enum, you can treat it as a regular JS object. In this case, you may explore it using Object.entries:

Object.entries(myEnum)

will give you an array containing key-value pairs:

[["name1","my name"],["name2","my other name"],["name3","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

A TypeScript class utilizing a static variable with the singleton design pattern

I have a query regarding the most effective way to code this scenario: Within a class, I require a static variable that is accessible throughout the entire project: connection Singleton without namespace: class Broker { static connection: Connection = u ...

having difficulty accessing the value within the Angular constructor

My current issue arises when I click on a button and set a value within the button click method. Despite declaring the variable in the constructor, I am unable to retrieve that value. The code snippet below demonstrates this problem as I keep getting &apos ...

Is it possible for an object's property specified in a TypeScript interface to also incorporate the interface within its own declaration?

While it may seem like an unusual request, in my specific scenario, it would be a perfect fit. I am working with an object named layer that looks something like this: const layer = { Title: 'parent title', Name: 'parent name', ...

Compose a message directed to a particular channel using TypeScript

Is there a way to send a greeting message to a "welcome" text channel whenever a new user joins the server (guild)? The issue I'm running into is that, when I locate the desired channel, it comes back as a GuildChannel. Since GuildChannel does not hav ...

The pipe in Angular 2.0.0 was not able to be located

Error: Issue: Template parse errors: The 'datefromiso' pipe is not recognized Custom Pipe: import {Pipe, PipeTransform} from "@angular/core"; @Pipe({ name: 'datefromiso' }) export class DateFromISO implements P ...

Increasing the number of service providers in Angular2-4 directives

Is there a way to apply both * to a string? Below is the code snippet I am working with: <a class="sidenav-anchor" *ngIf="!item.hasSubItems()" md-list-item md-ripple [routerLink]="[item.route]" routerLinkActive="active" [routerLinkActiveOptions]="{ex ...

fp-ts/typescript steer clear of chaining multiple pipes

Is there a more concise way to handle nested pipes in fp-ts when working with TypeScript? Perhaps using some form of syntactic sugar like Do notation? I'm trying to avoid this kind of nested pipe structure: pipe( userId, O.fold( () => set ...

Determining the inner type of a generic type in Typescript

Is there a way to retrieve the inner type of a generic type in Typescript, specifically T of myType<T>? Take this example: export class MyClass { myMethod(): Observable<{ prop1: string, ... }> { .... } } type myClassReturn = ReturnTy ...

Retrieve unique elements from an array obtained from a web API using angular brackets

I've developed a web application using .NET Core 3.1 that interacts with a JSON API, returning data in the format shown below: [ { "partner": "Santander", "tradeDate": "2020-05-23T10:03:12", "isin": "DOL110", "type ...

I want to know the most effective way to showcase particular information on a separate page using Angular

Recently, I've been working with a mock json file that contains a list of products to be displayed on a Product page. My goal is to select a specific product, such as 'Product 1', and have only that product's information displayed on th ...

How do I define the type of a class property in TypeScript?

I am currently working on my own implementation of Client-side rendering and I need to define the data structure for my route object. The format is shown below: import Post from './Post' export const route = { path: '/post', c ...

Explicit declaration of default parameters

Check out the helpful solution In regard to the following code snippet, type C = { a: string, b: number } function f({ a, b } = {a:"", b:0}): void { // ... } Can you explain the syntax for explicitly typing the default parameter? ...

Can an Angular application be developed without the use of the app-root tag in the index.html file?

I'm a newcomer to Angular and I'm trying to wrap my head around how it functions. For example, if I have a component named "login", how can I make Angular render it directly? When I try to replace the app-root tag with app-login in index.html, n ...

Acquire information from an Angular service and output it to the console

I am having trouble logging data from my service file in the app.component file. It keeps showing up as undefined. Below is the code snippet: service.ts getBillingCycles() { return this.http.get('../../assets/download_1.json'); }; app.com ...

Angular 6: The Promise<any> is incompatible with the LeagueTable type

Recently delving into Angular and attempting to retrieve JSON League Table data from the API, I encountered an error message stating Type 'Promise' is not assignable to type 'LeagueTable'. leaguetable.service.ts import { Injectable } ...

Effortless implementation of list loading with images and text in the Ionic 2 framework

Can someone provide guidance on creating a lazy loading list with both images and text? I understand that each image in the list will require a separate http request to download from the server. Should caching be implemented for these image downloads? Addi ...

Unable to use console log in shorthand arrow function while working with Typescript

When debugging an arrow function in JavaScript, you can write it like this: const sum = (a, b) => console.log(a, b) || a + b; This code will first log a and b to the console and then return the actual result of the function. However, when using TypeSc ...

Fire the BehaviorSubject with the identical value following a mutation

I am working with a BehaviorSubject where I have to make changes through mutation (for reasons beyond my control). I need to trigger the BehaviorSubject for subscriptions whenever there are changes. Is there another approach I can take instead of using: ...

What could be preventing my state from changing to false when I click the close button on the menu?

Despite initializing my state to false, the problem arises when I open and close my menu. The state never actually becomes false, causing the closing animation of the NavBar to not run as expected. The component: import CloseButton from "./CloseButto ...

Different ways to convert a date object to instant type in Angular without considering the timestamp

I have a function that converts a Date to a timestamp, but it includes the timezone, which I don't want. I only need the date with no timezone information in Instant type. convertDateToTimeStamp(date: any) { return Date.parse(date) / 1000; } Befor ...