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

Websocket onmessage event triggered just one time

I have implemented a basic WebSocket client in an Angular 6 application. Everything seems to be working fine, except for the fact that both socket.onmessage and socket.addEventListener('message' are only triggered once. There are no errors in th ...

Setting the initial state for a React toggle custom hook

After clicking a chevron button, an accordion component below it expands to display its children components. The goal is to ensure that each chevron button operates independently so that only the clicked button expands its related accordion. Upon initial ...

TSX implementation of a paginator with an ellipse in the center

Looking to add ellipses in the Pagination, specifically when there are more than 10 pages (e.g., 1 2 3 4 ... 11 12 13 14). I've tried various methods but need guidance as a beginner. Can anyone suggest changes based on my code to help me achieve this? ...

What could be causing the lack of updates to my component in this todo list?

Based on my understanding, invoking an action in MobX should trigger a rerender for the observer. However, when I call the handleSubmit method in my AddTask component, it doesn't cause the TaskList observer to rerender. Should I also wrap AddTask in a ...

React-snap causing trouble with Firebase

I'm having trouble loading items from firebase on my homepage and I keep running into an error. Does anyone have any advice on how to fix this? I've been following the instructions on https://github.com/stereobooster/react-snap and here is how ...

Updating the React State is dependent on the presence of a useless state variable in addition to the necessary state variable being set

In my current setup, the state is structured as follows: const [items, setItems] = useState([] as CartItemType[]); const [id, setId] = useState<number | undefined>(); The id variable seems unnecessary in this context and serves no purpose in my appl ...

Overlooking errors in RxJs observables when using Node JS SSE and sharing a subscription

There is a service endpoint for SSE that shares a subscription if the consumer with the same key is already subscribed. If there is an active subscription, the data is polled from another client. The issue arises when the outer subscription fails to catch ...

Error: Unable to locate the specified Typescript function

For the source code, please visit https://github.com/zevrant/screeps I am encountering an issue with my implementation of interfaces in TypeScript. When trying to call the implemented interface, I am getting the following error: "TypeError: spawn.memory.t ...

RXJS: Introducing a functionality in Observable for deferred execution of a function upon subscription

Implementing a Custom Function in Observable for Subscribers (defer) I have created an Observable using event streams, specifically Bluetooth notifications. My goal is to execute a function (startNotifictions) only when the Observable has a subscriber. ...

What is the best way to incorporate Tradingview's JavaScript into the render function of a React Typescript

I'm trying to incorporate some widgets into my Typescript React component. Here is the embed code export default class App extends React.Component { render(): ReactNode { return ( <div> Chart test <div className= ...

Using TypeScript to destructure by providing types

I encountered an issue while trying to destructure some code. The error message Property 'name' does not exist on type '{}'. is appearing. I thought about using let user:any = {}; as a workaround, but that goes against the eslint rule o ...

How does a brand new installation of VSCode believe it comes pre-equipped with TypeScript capabilities?

Operating on Windows 10 Enterprise, After investing several hours and experimenting on various VMs, Interesting Observation #1 Upon opening a .ts file in vscode, it appears to be recognized as TypeScript 2.3.4 as per the screenshot provided below: http ...

Performing a conditional query on a Many-to-Many relationship in TypeORM

Operating under a many-to-many relationship between Category and Product entities In need of filtering products based on category ID Attempted to implement the following code after referring to some examples, but encountered difficulties in making it fun ...

Angular2/Typescript: Transforming a Javascript/Typescript Date into a C# DateTime string on the client side

Currently immersed in an Angular2/Typescript project, I am faced with the task of sending a date to a C# backend. Despite my extensive research, all I could uncover through Google searches was information on converting the date on the backend side. My la ...

How should a React Testing Library wrapper be properly typed in a TypeScript environment?

There's this code snippet from Kent C. Dodd's library that I find extremely helpful import * as React from 'react' import {render as rtlRender} from '@testing-library/react' import {ThemeProvider} from 'components/theme& ...

Error encountered when attempting to utilize ngTemplate to embed filter within a table

I am facing an issue with a component that includes a primeng table. Within a table row, I have an ng-container to project a p-columnFilter into the table from an external source. However, when trying to pass the filter into the template, I encounter a Nul ...

The origin of the Angular img src becomes blurred when invoking a function

I want to dynamically change the image src by calling a function that returns the image path. However, when I attempt to do so using the code below, the image element displays as <img src(unknown)/> component.ts: getMedia(row) { this.sharedData ...

methods for array filtering in typescript

How do I filter an array in TypeScript? I attempted the following findAllPersonsNotVisited():Observable<Person[]> { var rightNow = new Date(); var res = rightNow.toISOString().slice(0,10).replace(/-/g,"-"); return this.db.list(& ...

Issue with displaying entire object using Jest and console.dir

I'm having trouble displaying an error in my Jest test because it's not showing all the levels as expected. import util from 'util' describe('Module', () => { it('should display all levels WITHOUT util', () =& ...

Clicked but nothing happened - what's wrong with the function?

For my project, I have incorporated tabs from Angular Material. You can find more information about these tabs here. Below is the code snippet I am using: <mat-tab-group animationDuration="0ms" > <mat-tab></mat-tab> < ...