Skip to content

A flag to disable reverse mapping in number enumsΒ #57134

Closed
@y-nk

Description

@y-nk

πŸ” Search Terms

"number" "enum" "Object.values"

βœ… Viability Checklist

⭐ 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

playground link

πŸ’» Use Cases

  1. What do you want to use this for?
    writing typeguards in the same way for string and number enums

  2. What shortcomings exist with current approaches?
    there's a need for a filtering pass on enum set

  3. 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]
    })
}

playground link

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions