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?
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
I figure out that we can do something like:
Not sure if this is the best way (more efficient/cleaner) way to do it.
PS: You can test it here
Obviously, there’s
but there’s also
Object.values
:However, this only works if your enum does not contain numerical values.
Playground
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