skip to Main Content

I have the following enum:

enum Animes {
    OnePiece = 'One Piece',
    Naruto = 'Naruto',
    Bleach = 'Bleach'
}

What is the best way to convert this enum to a Set?

3

Answers


  1. Chosen as BEST ANSWER

    I figure out that we can do something like:

    const animes = new Set(Object.values(Animes))
    

    Not sure if this is the best way (more efficient/cleaner) way to do it.

    PS: You can test it here


  2. Obviously, there’s

    new Set([Animes.OnePiece, Animes.Naruto, Animes.Bleach])
    

    but there’s also Object.values:

    const anime = new Set(Object.values(Animes));
    //    ^^^^^ inferred as Set<Animes>
    

    However, this only works if your enum does not contain numerical values.

    enum What { A, B, C }
    
    new Set(Object.values(What)) // Set { "A", "B", "C", "0", "1", "2" }
    

    Playground

    Login or Signup to reply.
  3. Given that enums in Typescript are just objects, you could do: const mySet = new Set(Object.values(Animes));.

    This would be incorrect for numeric enums since they have this weird bidirectional access, in that case just use: const mySet = new Set(Object.values(MyEnum).filter(x => typeof x === "string"));

    Although this is the simplest way, and due to how these functions are typed, you’d lose the type information

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search