How to access enums dynamically using key in TypeScript

export enum MyEnum{
    Option1,
    Option2,
    Option3
}


string selection = 'Option1';

MyEnum[selection] results in an error:

The type string cannot be assigned to the type MyEnum

On the other hand: MyEnum['Option1'] works as expected.

I'm looking to utilize MyEnum[selection] (in a function that returns a MyEnum), with the condition that selection is a dynamically determined value corresponding to one of the valid enum options. How should I approach this?

Answer №1

There are a couple of methods to accomplish this goal.

  1. If you wish to retain the robust typechecking feature of TS, opt for this approach:

    MyEnum[x as keyof typeof MyEnum] 
    

Using typeof MyEnum will establish an interface representing the underlying MyEnum object, while keyof will yield a union of string literals, each one being a key within the MyEnum object (essentially providing a list of keys associated with a given object/class).

  1. To simply disable type checking for the subsequent line, akin to asserting the type of MyEnum as <any> as demonstrated in @annepic's response:
  2. // @ts-ignore 
    MyEnum[x] 
    

Additional remark: It is advisable to always enable the Strict flag in tsconfig under all circumstances (reserving ignoring type checking for only rare exceptional instances like described above). This configuration compels developers to define the structure/type/interface for everything, resulting in a highly self-documenting and explanatory codebase – beneficial for both your future self and other maintainers. By adhering to strict formatting rules set forth by JSDoc for documenting JS code through comments, one can ascertain how a class/object is formatted and how a function should be used with absolute certainty, even without delving into its implementation details. The additional advantages of enabling the Strict flag can be found in the primary TypeScript documentation.

Answer №2

Success achieved with the following approach: return (<any>MyEnum)[x];

Answer №3

Your string variable x declaration is incorrect. The correct way to declare it is as follows:

export enum MyEnum{
    Option1,
    Option2,
    Option3
}


var x = 'Option1';
MyEnum[x];

Answer №4

It seems like what you need to do is explicitly specify the type of the selected item in your enum as that enum itself. Here's an example:

export enum MyEnum{
  Option1,
  Option2,
  Option3
}

function getEnum(x = 'Option1'):MyEnum {
  return <MyEnum>MyEnum[x];
}

The error message you mentioned, "Type string is not assignable to type MyEnum," is actually caused by the function return type not matching your enum. Some solutions involve converting the enum to an object, but that won't work with a function that has a return type matching the enum.

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 a model for a different user involves several steps that can be easily

Recently, I have been working on a project involving user interactions such as following other users and viewing their content. Using technologies like Prisma, GraphQL, and Nexus, I decided to create a following model today. The model structure is as follo ...

Discovering the most recent 10 date elements in a JSON object within a React application

I have an array of objects containing a date element. My goal is to identify the 10 most recent dates from this element and display them in a table format. When I attempt to render these dates using a mapping technique that targets each data with data.date ...

How to upload files from various input fields using Angular 7

Currently, I am working with Angular 7 and typescript and have a question regarding file uploads from multiple input fields in HTML. Here is an example of what I am trying to achieve: <input type="file" (change)="handleFileInput($event.target.files)"&g ...

What is the correct way to close an ngx-contextmenu in an Angular application?

In my angular project, I implemented an ngx-contextmenu. Within one of my components, the template includes the following code: <div... [contextMenu]="basicMenu"> <context-menu>..... </div> After some time, the component with the conte ...

What is the best way to handle asynchronous actions while initializing a database in Next.js?

My goal is to create tables during the database initialization stage with a structure like this: CREATE TABLE IF NOT EXISTS users ( "id" SERIAL PRIMARY KEY, "created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "name&quo ...

Are the functions 'useEffect' and 'useCallback' being repetitively used in this case?

I have implemented a custom hook in my React application to manage back navigation actions (POP). The functionality is operational, but I can't help but notice that useCallback and useEffect seem to be performing similar tasks. Here is the snippet of ...

The presence of v-if does not depend on the model value to toggle the element

I have a scenario where I want to hide the dropdown menu for US states if a different country other than the US is selected. The code snippet I am using to achieve this functionality is shown below: <b-row v-for="demo in demographics" :key=&qu ...

Break apart the string and transform each element in the array into a number or string using a more specific type inference

I am currently working on a function that has the ability to split a string using a specified separator and then convert the values in the resulting array to either strings or numbers based on the value of the convertTo property. Even when I call this fun ...

Exploring the TypeScript Type System: Challenges with Arrays Generated and Constant Assertions

I am currently grappling with a core comprehension issue regarding TypeScript, which is highlighted in the code snippet below. I am seeking clarification on why a generated array does not function as expected and if there is a potential solution to this pr ...

``I would like to discuss the use of TypeScript in returning a boolean value from

I am new to Angular and Typescript, and I need help returning a boolean value from a function that I can use in *ngIf. I want this process to be seamless. Can someone assist me with this? canView = false; getView() { this.permissionService.getPermissi ...

Why isn't the customer's name a part of the CFCustomerDetails class?

Currently, I am utilizing the cashfree-pg-sdk-nodejs SDK to integrate Cashfree payment gateway into my application. Upon examining their source code, I noticed that the CFCustomerDetails class does not include the customerName attribute. https://i.stack.i ...

How to open a print preview in a new tab using Angular 4

Currently, I am attempting to implement print functionality in Angular 4. My goal is to have the print preview automatically open in a new tab along with the print popup window. I'm struggling to find a way to pass data from the parent window to the c ...

Decide on the chosen option within the select tag

Is there a way to pre-select an option in a combobox and have the ability to change the selection using TypeScript? I only have two options: "yes" or "no", and I would like to determine which one is selected by default. EDIT : This combobox is for allow ...

Is it possible to use an Enum as a type in TypeScript?

Previously, I utilized an enum as a type because the code below is valid: enum Test { A, B, } let a: Test = Test.A However, when using it as the type for React state, my IDE displays an error: Type FetchState is not assignable to type SetStateActi ...

Could you explain the distinction between npm install and sudo npm install?

I recently switched to using linux. To install typescript, I ran the following command: npm i typescript Although there were no errors during the installation process, when I checked the version by typing tsc --version, I encountered the error message -bas ...

Testing a NestJS service with multiple constructor parameters can be done by utilizing various techniques such as dependency

Content When testing a service that needs one parameter in the constructor, it's essential to initialize the service as a provider using an object instead of directly passing the service through: auth.service.ts (example) @Injectable() export class ...

Reduce the size of the JSON file located in the Assets folder during an Angular build

What is the most effective method to compress JSON files in an Angular production build? I currently have a JSON file in the assets folder that remains unchanged when the production build is completed. During development, the file appears as the Developme ...

Angular failing to retrieve URL parameters correctly

As I was trying to retrieve URL queries like www.website.com?a:b, I decided to follow the guidance provided in a particular Angular tutorial. This official tutorial (accessible via this link) instructed me to implement the following simple code snippet wit ...

AngularJS Currency Converter - Converting Currencies with Ease

I have a question regarding the most efficient way to handle currency conversion on a webpage. Currently, I have multiple input fields displaying different currencies. When a user clicks on the currency conversion button, a modal popup appears. After the ...

ESLint and Prettier are butting heads when trying to run their commands consecutively

My package.json file includes two commands: "format": "prettier --write \"{src,{tests,mocks}}/**/*.{js,ts,vue}\"", "lint": "eslint . -c .eslintrc.js --rulesdir eslint-internal-rules/ --ext .ts,.js,.vue ...