Description
π Search Terms
"number" "enum" "Object.values"
β Viability Checklist
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
β Suggestion
A simple configuration flag to disable explicitly reverse mapping for enums (#30487)
enum Foobar {
FOO,
BAR,
}
console.log(Object.keys(Foobar)) // ["0", "1", "FOO", "BAR"]
console.log(Object.values(Foobar)) // ["FOO", "BAR", 0, 1]
While this is intended behavior, it can be found as unnatural behavior since string enums don't behave the same way. I don't mind the current behavior, but having a flag to align both number and string enums would make sense, at least to me.
π Motivating Example
enum Foobar {
FOO,
BAR,
}
function isFoobar(arg: any): arg is Foobar {
return Object.values(Foobar).includes(arg)
}
console.log(isFoobar(Foobar.FOO)) // ok
console.log(isFoobar('FOO')) // should not pass, only 0 & 1 (as number) should be allowed
π» Use Cases
-
What do you want to use this for?
writing typeguards in the same way for string and number enums -
What shortcomings exist with current approaches?
there's a need for a filtering pass on enum set -
What workarounds are you using in the meantime?
// inefficient but clean
function isFoobar(arg: any): arg is Foobar {
return Object
.values(Foobar)
.filter((v: any) => !isNaN(v))
.includes(arg)
}
// efficient but amazingly ugly
function cleanEnum(enumType: any) {
Object.entries(enumType)
.forEach(([k, v]: [any, any]) => {
if (isNaN(v)) delete enumType[k]
})
}
Other considerations
Maybe another approach would be to have a different way of writing enums so that they match instanceof
but i can't think of anything which is not ugly and hacky.
Or since enums emit JS code, have their own .is()
type guard function generated would be nice too.