Unfortunately, this is just how enums function. They are essentially a way to assign names to numerical values for easier understanding. Ultimately, they boil down to numbers, making it difficult to determine the original array based solely on a number like 3
.
Below is an example in TypeScript, or you can view it on TS Playground
enum enumA {
One = 1,
Two = 2,
Three = 3
}
enum enumB {
One = 1,
Two = 2,
Three = 3
}
var x: enumA | enumB = enumB.Three;
console.log(typeof x, x);
console.log(typeof enumB, enumB)
This will output:
"number", 3
"object", {
"1": "One",
"2": "Two",
"3": "Three",
"One": 1,
"Two": 2,
"Three": 3
}
Enums do not provide enough information to trace back to their source as desired.
If you must use enums, one workaround is to include a second property to store the entire enum and its value separately:
TS Playground link
enum enumA {
One = 1,
Two = 2,
Three = 3
}
enum enumB {
One = 1,
Two = 2,
Three = 3
}
interface IGenericEnum {
[s: number]: string
}
function test<T = IGenericEnum>(list: T, val: keyof T){
console.log(list, val);
}
test(enumA, "One");
While not perfect, this approach provides a bit more information by separating enum values into individual fields. It remains strongly typed, preventing errors like attempting test(enumA, "Foo")
.