Last active
April 4, 2025 15:41
-
-
Save acquitelol/2f80d60feb8bdc00ca5d239d76630ce5 to your computer and use it in GitHub Desktop.
An enum implementation which creates real TypeScript objects with number literals out of an enum string.
This file contains hidden or 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
| type EnumToObject<Keys extends string[], Acc extends string[] = []> = | |
| Keys extends [infer First extends string, ...infer Rest extends string[]] | |
| ? { [K in First]: Acc["length"] } & EnumToObject<Rest, [...Acc, First]> | |
| : {}; | |
| type Split<T extends string, D extends string, Acc extends string[] = []> = | |
| Trim<T> extends `${infer First}${D}${infer Rest}` | |
| ? Split<Trim<Rest>, D, [...Acc, Trim<First>]> | |
| : [...Acc, Trim<T>] | |
| type Whitespace = " " | "\n" | "\t"; | |
| type Trim<T extends string> = | |
| T extends `${Whitespace}${infer R}` | |
| ? Trim<R> | |
| : T extends `${infer R}${Whitespace}` ? Trim<R> : T; | |
| function enu_m<T extends string>(x: T) { | |
| return x.split('\n').filter(Boolean).reduce( | |
| (acc, cur, i) => ({ ...acc, [cur.trim()]: i }), | |
| {} as EnumToObject<Split<T, '\n'>> | |
| ); | |
| } | |
| const x = enu_m(` | |
| First | |
| Second | |
| Third | |
| Fourth | |
| Fifth | |
| `); | |
| // x.Fourth: 3 | |
| console.log(x.Fourth); // 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment