There are two ways to achieve this
⭐️ 1st: 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 given object/class).
⭐️ 2nd 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]
Extra 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/interface
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.