JᴀʏMᴇᴇ
JᴀʏMᴇᴇ

Reputation: 276

Passing enum type as parameter in typescript

I have a function:

public doSomethingWithEnum(enumType) {
   // Iterate over enum keys with Object.keys(enumType)
}

And I can use it like so:

export enum MyEnum { SomeEnumValue = 'SomeEnumValue', SomeOtherValue = 'SomeOtherValue' }

doSomethingWithEnum(MyEnum);

That's fine, it works. The problem is that I'd like a type on that parameter so I can pass it any enum. At the moment, it might aswell be :any which I think is far too open.

Is there any way of restricting/specifying the type of that parameter?

What I've Tried

I know it's possible to restrict this by listing known types e.g.:

doSomethingWithEnum(enumType: MyEnum | MyOtherEnum)

But I need it more scalable than that, I don't want to have to append a type every time a different consumer needs to call the service.

Upvotes: 5

Views: 8581

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85251

Enums are basically objects with key/value pairs, where the value is either a string or a number. So if you want to make a function that accepts literally any enum you can do:

enum Example {
    foo,
    bar
};

const doSomethingWithEnum = (en: Record<string, string | number>) => {
    Object.keys(en).forEach(key => console.log(key));
}

doSomethingWithEnum(Example);

This does mean that you could construct a non-enum object with strings/numbers as its keys and pass that in too.

Upvotes: 3

Related Questions