1

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

Code sample

2
  • 6
    please paste code not images of your code. It helps people trying to help you. Commented Jul 19, 2017 at 19:35
  • Thanks the link you provide contains the best solution for my case Commented Jul 20, 2017 at 13:50

2 Answers 2

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];
}
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
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. stackoverflow.com/questions/30774874/…
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;

3 Comments

Thanks this solution is working
This works, but I really wish there were a better way. I don't quite understand why we can't make a function like: function getText<E>(enumValue: number, typeEnum: E): string;
Use unknown instead of any

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.