0

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'

KJ3
  • 5,168
  • 4
  • 33
  • 53
  • [`Enumerator`](https://microsoft.github.io/PowerBI-JavaScript/interfaces/_node_modules_typedoc_node_modules_typescript_lib_lib_scripthost_d_.enumerator.html) and enum are two very different things. – Shivam Singla Apr 08 '21 at 04:40
  • 2
    Could you please state a scenario where you can accept "any" enum? – Shivam Singla Apr 08 '21 at 04:43
  • Enums are unsafe. DOn't do this under any circumstances. Take a look on this example https://www.typescriptlang.org/play?#code/FAUwdgrgtgBAgmAllAhgGxgb2DGARAewHMAaYAX2FElgDECCATLHGABURDMuADMIwAYwAuiAmHiDBIAA7CA8mBAAKcSABcMGgCMQAJwCULXIPEBnAmhAA6NMVVKDFKnCmyFS5QmTprhIgYA3MCu0nKKKvRM1hwgQUA . Also enums are mutable – captain-yossarian from Ukraine Apr 08 '21 at 05:49

1 Answers1

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

LevPewPew
  • 159
  • 7