1

I'd like to create a function that accepts any Enum. For example

function AcceptOne(one: Enumerator) {}

With an enum

enum Animal {
    Dog = 'Dog'
}

And then call

AcceptOne(Animal.Dog);

But I get the error

Argument of type 'Animal' is not assignable to parameter of type 'Enumerator'

3
  • Enumerator and enum are two very different things. Commented Apr 8, 2021 at 4:40
  • 2
    Could you please state a scenario where you can accept "any" enum? Commented Apr 8, 2021 at 4:43
  • Enums are unsafe. DOn't do this under any circumstances. Take a look on this example typescriptlang.org/play?#code/… . Also enums are mutable Commented Apr 8, 2021 at 5:49

1 Answer 1

0

"It's not possible to ensure the parameter is an enum, because enumerations in TS don't inherit from a common ancestor or interface.", taken from here.

Assuming your enums will only have string values, you may as well just change the one type to string and then any of these enums value will work:

enum Animal {
    Dog = 'Dog'
}

enum Food {
    Pie = 'Pie'
}

function AcceptOne(one: string) {
  console.log(one)
}

AcceptOne(Animal.Dog);
AcceptOne(Food.Pie);

Sandbox link

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.