Last active
February 14, 2023 20:10
-
-
Save aparx/b14d6b1464b6492fdc5526a882473e02 to your computer and use it in GitHub Desktop.
typescript enums without using enum
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
type EnumKey<EnumType> = keyof EnumType; | |
type IdentityEnum<T> = T extends Array<infer E extends string> ? { | |
readonly [P in T[keyof T] as E]: E | |
} : never; | |
type IdentityEnumConstructor = { | |
<T extends string[]>(...values: T): IdentityEnum<T>; | |
new <T extends string[]>(...values: T): IdentityEnum<T>; | |
}; | |
type EnumField<T> = T extends IdentityEnum<string[]> | |
? keyof T : T extends string | |
? T : never; | |
const IdentityEnum = function<T extends string[]>(...names: T) { | |
const obj: Partial<IdentityEnum<T>> = {}; | |
for (const name of names) { | |
(obj as any)[name] = name; | |
} | |
return {...obj} as const; | |
} as IdentityEnumConstructor; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example
Example on typescript playground