1

I have the following code:

enum MY_ENUM {
    A,
    B,
    C
}

type MY_TYPE = {
    field: MY_ENUM
}

// Error: Type '{ field: string; }[]' is not assignable to type 'MY_TYPE[]'.
const myArray: MY_TYPE[] = Object.keys(MY_ENUM).map(key => {
    return {
        field: key,  // key is a string, but I want it to be MY_ENUM
    }
})

It gives an error on myArray, saying string is not assignable to type 'MY_TYPE'.`, so how do I get the enum typed key instead of string? Or in another word, how can I iterate enum, gets the actual enum typed key but not its string representation?

example

Kallzvx
  • 594
  • 7
  • 23
  • 2
    Does this answer your question? [Why doesn't Object.keys return a keyof type in TypeScript?](https://stackoverflow.com/questions/55012174/why-doesnt-object-keys-return-a-keyof-type-in-typescript) – Jared Smith Jul 15 '22 at 14:28
  • @JaredSmith Thanks, the link is helpful but does not give a solution/workaround. – Kallzvx Jul 15 '22 at 14:41
  • 2
    That's because there isn't one. It's simply not possible to guarantee *compile-time* type safety when you are iterating the properties of an object at *runtime*. You will need to do a runtime check that the object keys are actually members of the enum and cast them appropriately. See also [this answer](https://stackoverflow.com/a/66233215/3757232) wrt to narrowing types. – Jared Smith Jul 15 '22 at 14:43

0 Answers0