Skip to content

Instantly share code, notes, and snippets.

@tanepiper
Forked from rauschma/create-enum.ts
Created March 8, 2025 15:52
Show Gist options
  • Save tanepiper/0876127eba4ed7205dbbf0922311e492 to your computer and use it in GitHub Desktop.
Save tanepiper/0876127eba4ed7205dbbf0922311e492 to your computer and use it in GitHub Desktop.
createEnum(): helper for creating enum objects
// 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