-
-
Save tanepiper/0876127eba4ed7205dbbf0922311e492 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` is better for performance 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