How can i pass enum type defined as parameter. Check at my usage on the bottom of the following picture.
-
6please paste code not images of your code. It helps people trying to help you.toskv– toskv2017-07-19 19:35:03 +00:00Commented Jul 19, 2017 at 19:35
-
Thanks the link you provide contains the best solution for my caseuser3119630– user31196302017-07-20 13:50:45 +00:00Commented Jul 20, 2017 at 13:50
Add a comment
|
2 Answers
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];
}
3 Comments
user3119630
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.
HankScorpio
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.fantapop
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/…
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
user3119630
Thanks this solution is working
HankScorpio
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;avalanche1
Use
unknown instead of any