0

How can i pass enum type defined as parameter. Check at my usage on the bottom of the following picture.

Code sample

user3119630
  • 315
  • 1
  • 4
  • 9

2 Answers2

2

I don't think there's an easy way to say "only support enums" like you want. You have some options though. You can keep adding enums you want to support:

enum Color {};
enum Car {};
type SupportedEnums = typeof Color | typeof Car;
function getText(enumValue: number, typeEnum: SupportedEnums) {
    retrun `${enumValue}(${typeEnum[enumValue]})`;
}

Or, instead of maintaining SupportedEnums, just use any type.

====

Original answer:

You can refer to the type by using typeof:

getText(enumValue: number, typeEnum: typeof Color): string {
    return typeEnum[enumValue];
}
Sean
  • 337
  • 2
  • 7
  • This won't work in my case since this getText function will be use with 2 different enum type. See my usage case at the bottom of the image. I'm looking for a generic function to pass any type of enum. – user3119630 Jul 20 '17 at 13:37
  • This also doesn't work for me. I get this error: `TS2693: 'Color' only refers to a type, but is being used as a value here.` – HankScorpio Aug 22 '19 at 20:43
  • I posted an update back to the post this one was marked as a duplicate of. IMO an improvement on the type checking at the expense of more code. https://stackoverflow.com/questions/30774874/enum-as-parameter-in-typescript/62857364#62857364 – fantapop Jul 12 '20 at 05:20
0

For any enum, use any.

function getText(enumValue: number, typeEnum: any): string;

To restrict the possible enums, use the union type.

function getText(enumValue: number, typeEnum: typeof Car | typeof Color): string;
Rodris
  • 2,603
  • 1
  • 17
  • 25