Last active
March 25, 2025 12:50
-
-
Save rauschma/867583e0a09e4dbc63f9c59ac38f956f to your computer and use it in GitHub Desktop.
createEnum(): helper for creating enum objects
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
// More information on enum objects as an alternative to enums: | |
// https://2ality.com/2025/01/typescript-enum-patterns.html#alternative-to-enum%3A-object-literal-1 | |
/** | |
* Returns an enum object. Adds the following improvements: | |
* - Sets the prototype to `null`. | |
* - Freezes the object. | |
* - The result has the same type as if `as const` had been applied. | |
*/ | |
function createEnum< | |
// The two type variables are necessary so that the result has specific | |
// property value types. | |
T extends { [idx: string]: V }, | |
V extends | |
| undefined | null | boolean | number | bigint | string | symbol | |
| object | |
>(enumObj: T): Readonly<T> { | |
// Copying `enumObj` produces “faster” objects than Object.setPrototypeOf() | |
return Object.freeze({ | |
__proto__: null, | |
...enumObj, | |
}); | |
} | |
const Tree = createEnum({ | |
Maple: 'Maple', | |
Oak: 'Oak', | |
}); | |
type X = typeof Tree; | |
// { | |
// readonly Maple: "Maple"; | |
// readonly Oak: "Oak"; | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment