Obtaining the Enum key in Angular using the Enum type instead of a string value

Is there a way to retrieve the key of an enum not as a string, but with the enum itself? https://stackblitz.com/edit/typescript-av8rkx

enum Widgets {
  Foo = "this is foo",
  Bar = "this is bar"
}

const current = "this is foo";
console.info(current); // 'this is foo';

let enumKey = Object.keys(Widgets)[Object.values(Widgets).indexOf(current)];
console.log(typeof(enumKey)) // here it returns string

I want to be able to access the enum using the 'enumKey' mentioned above.

Widgets[enumKey]

Unfortunately, this method is not working for me. Can anyone provide assistance on how to achieve this? Thanks

Answer №1

If you ever need to create a "reverse" enum, the following code snippet demonstrates how to achieve it:

type Inverted<T extends Record<any, string>> = { [K in keyof T as T[K]]: K }
type InvertedColors = Inverted<typeof Colors>
const InvertedColors: InvertedColors =
    Object.entries(Colors)
        .reduce((acc, [key, value]) => (acc[value] = key, acc), {} as any)

const currentColor = "this is red"
const enumKeyColor = InvertedColors[currentColor] // "Red"
const nextColor = Colors[enumKeyColor] // Colors.Red

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

Adonisjs latest version (v5) model creation command malfunctioning

Using Adonisjs v5 The controller command works fine with: node ace make:controller Posts However, the new model creation command is not working: node ace:make model Post When running the make model command, an error occurs: An error message stating &ap ...

Enhance your coding experience with Angular Apollo Codegen providing intelligent suggestions for anonymous objects

Currently, I am exploring the integration of GraphQL with Angular. So far, I have been able to scaffold the schema successfully using the @graphql-codegen package. The services generated are functional in querying the database. However, I've noticed ...

Combine Sonarqube coverage with Istanbuljs/NYC for enhanced code analysis

In my typescript project, we utilize a Jenkins pipeline to run all functional tests in parallel after building the main container. Towards the end of the pipeline, we conduct a code coverage check and then transfer the results to sonarqube. Below is an ex ...

Error: Trying to access property '2' of a null value

I’ve been working on a project using Next.js with TypeScript, focusing on encryption and decryption. Specifically, I’m utilizing the 'crypto' module of Node.js (@types/nodejs). However, I encountered an error while attempting to employ the &a ...

Convert your socket.io syntax to TypeScript by using the `import` statement instead

const io = require('socket.io')(server, { cors: { origin: '*', } }); Is there a way to convert this code to TypeScript using the syntax import {} from ''; ...

Prevent a React component from unnecessarily re-rendering after a property has been set

I am working on a react component that displays a streaming page similar to the one shown in this image. Here is a snippet of the code : const [currentStream, setCurrentStream] = useState<IStream>(); const [currentStreams] = useCollectionData<ISt ...

When attempting to register a custom Gamepad class using GamepadEvent, the conversion of the value to 'Gamepad' has failed

I have been working on developing a virtual controller in the form of a Gamepad class and registering it. Currently, my implementation is essentially a duplicate of the existing Gamepad class: class CustomController { readonly axes: ReadonlyArray<nu ...

When object signatures match exactly, TypeScript issues a warning

I am facing an issue with typescript while trying to use my own custom type from express' types. When I attempt to pass 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' as a parameter of type 'Context&a ...

Conceal object from inventory upon clicking

As someone who is new to React and Typescript, I am facing challenges in understanding how to hide a ticket from the list when the hide button is clicked. displayTickets = (tickets: Ticket[]) => { const filteredTickets = tickets.filter(t => ...

Angular version 6 allows for specifying input types as numbers and displaying two decimal digits after the comma

How can I format user input to display as currency with thousand separators in Angular? <input type="number" (ngModelChange)="calculateSum()" (change)="calculateAmount(invoiceQuota)" [ngModel]="invoiceQuota.controls.grossAmount.value"> I have attem ...

When using Typescript type aliases, make sure to let Intellisense display the alias name instead of the source

Take a look at this brief code snippet type A = number; declare function f(): A; const a = f(); // `a` is number, not A What could be the reason for TS displaying a: number instead of a: A? ...

Configuring rows in React datagrid

I am working on a component where I receive data from the backend and attempt to populate a DataGrid with it. Below is the code for this component: export const CompaniesHouseContainer: React.FC<Props> = () => { const classes = useStyl ...

Having trouble getting ng-click to function properly in TypeScript

I've been struggling to execute a function within a click function on my HTML page. I have added all the TypeScript definition files from NuGet, but something seems to be going wrong as my Click Function is not functioning properly. Strangely, there a ...

Issues with loading NextJS/Ant-design styles and JS bundles are causing delays in the staging environment

Hey there lovely folks, I'm in need of assistance with my NextJS and Ant-design application. The current issue is only occurring on the stagging & production environment, I am unable to replicate it locally, even by running: npm run dev or npm r ...

Angular progress tracker with stages

I have been exploring ways to create a progress bar with steps in Angular 12 that advances based on the percentage of progress rather than just moving directly from one step to another. This is specifically for displaying membership levels and indicating h ...

Can a reducer be molded in ngrx without utilizing the createReducer function?

While analyzing an existing codebase, I came across a reducer function called reviewReducer that was created without using the syntax of the createReducer function. The reviewReducer function in the code snippet below behaves like a typical reducer - it t ...

What is the TypeScript syntax for indicating multiple generic types for a variable?

Currently working on transitioning one of my projects from JavaScript to TypeScript, however I've hit a roadblock when it comes to type annotation. I have an interface called Serializer and a class that merges these interfaces as shown below: interfa ...

Disabling the last control in a formGroup when sorting an array with Angular

I am facing an issue with sorting an array based on a numeric control value inside a formGroup nested in another array: const toSort = [ ['key2', FormGroup: {controls: {order: 2}}], ['key1', FormGroup: {controls: {order: 1}}] ] ...

Exploring the potential of TypeScript with native dynamic ES2020 modules, all without the need for Node.js, while also enhancing

I have a TypeScript application that utilizes es16 modules, with most being statically imported. I am now looking to incorporate a (validator) module that is only imported in debug mode. Everything seems to be functioning properly, but I am struggling to f ...

Methods to acquire the 'this' type in TypeScript

class A { method : this = () => this; } My goal is for this to represent the current class when used as a return type, specifically a subclass of A. Therefore, the method should only return values of the same type as the class (not limited to just ...