#How to get the type of an enum

8 messages · Page 1 of 1 (latest)

weary fern
#

If I have a function that uses an enum as a parameter, how can I get the type of that enum, so I can return a value of the same type?

#

Let's say I have:

enum EFoo {
  VALE_1 = "Value 1",
  VALE_2 = "Value 2",
}

function test<O extends Object, K extends typeof O>(e: Object): K[] {
  // Do some things...
  // Return array of same type
}

const bar = test(EFoo); // Should be an array of type string
waxen void
#

Why is it array of type string?

weary fern
waxen void
#

They don't have to be strings

#

Still not sure what exactly you want but maybe this:

function test<E extends Record<string, unknown>>(e: E): E[keyof E][] {}
#

Do note that your function implementation might have issues if the enum isn't a string enum

#

You can change it to Record<string, string> to only allow string enums to be passed in