Last active
December 11, 2021 07:24
-
-
Save kevboutin/fcb76b328b3219131bce3ee291e331d2 to your computer and use it in GitHub Desktop.
Best way to do enum in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Season enums can be grouped as static members of a class | |
class Season { | |
// Create new instances of the same class as static attributes | |
static Summer = new Season("summer") | |
static Autumn = new Season("autumn") | |
static Winter = new Season("winter") | |
static Spring = new Season("spring") | |
constructor(name) { | |
this.name = name | |
} | |
} | |
// Now we can access enums using namespaced assignments | |
// this makes it semantically clear that "Summer" is a "Season" | |
let season = Season.Summer | |
// We can verify whether a particular variable is a Season enum | |
console.log(season instanceof Season) | |
// true | |
console.log(Symbol('something') instanceof Season) | |
// false | |
// We can explicitly check the type based on each enums class | |
console.log(season.constructor.name) | |
// 'Season' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment