Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

dynamically access enum in typescript by key

export enum MyEnum{
    Option1,
    Option2,
    Option3
}


string x = 'Option1';

MyEnum[x] throws an error:

Type string is not assignable to type MyEnum

however: MyEnum['Option1'] works.

I need to use MyEnum[x] though (in a method that returns a MyEnum), where x is a calculated value that results in one of the valid enum options, how do I go about it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two elegant ways to achieve this ??

?? 1st way: just simply turn off the type checking for the next line, which is similar to asserting the type of MyEnum to <any> as done in the @annepic 's answer

// @ts-ignore 
MyEnum[x] 

?? 2nd: If u still want to keep the powerful typechecking feature of TS, choose this

MyEnum[x as keyof typeof MyEnum] 

typeof MyEnum will create an interface that represents the MyEnum object behind the scene and keyof will return a union of string literals, each one is the key in the MyEnum object (in other words, keyof will return a list of keys of a particular object).

Note: Always turn on the Strict flag in tsconfig no matter what (u should only ignore type checking for a single line in very rare and special cases as done above). This configuration will force the developers to define the shape/type/structure for everything, which makes the entire codebase super self-documenting and self-explanatory, especially for your future self and code maintainers. U can quickly infer how a class/object is structured and how a function is used with 100% certainty without even looking at its implementation. JSDoc specifies a set of very strict formatting rules for documenting JS code using comments, but these comments often end up being out of date because they are not changed along with the function evolution. Other benefits of the Strict flag are mentioned in the TypeScript primary doc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...