Created
July 26, 2023 15:27
-
-
Save larvanitis/3f8e37845fc8b612021d3d8492c85245 to your computer and use it in GitHub Desktop.
TypeScript enum-like objects and util functions
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
// utils | |
type EnumValue<T> = T[keyof T]; | |
type EnumKey<T> = keyof T; | |
export function isEnumValue<T extends Record<string, unknown>>( | |
enm: T, | |
value: unknown | |
): value is EnumValue<T> { | |
return Object.values(enm).includes(value as any); | |
} | |
export function assertEnumValue<T extends Record<string, string | number>>( | |
enumObj: T, | |
value: unknown | |
): asserts value is EnumValue<T> { | |
if (!isEnumValue(enumObj, value)) { | |
const values = Object.values(enumObj) | |
.map((x) => JSON.stringify(x)) | |
.join(); | |
throw new Error(`Not an enum value: ${value}. Expected one of ${values}.`); | |
} | |
} | |
export function isEnumKey<T extends Record<string, unknown>>( | |
enm: T, | |
key: unknown | |
): key is EnumKey<T> { | |
return Object.keys(enm).includes(key as any); | |
} | |
export function assertEnumKey<T extends Record<string, string | number>>( | |
enumObj: T, | |
value: unknown | |
): asserts value is EnumKey<T> { | |
if (!isEnumKey(enumObj, value)) { | |
const keys = Object.keys(enumObj) | |
.map((x) => JSON.stringify(x)) | |
.join(); | |
throw new Error(`Not an enum key: ${value}. Expected one of ${keys}.`); | |
} | |
} | |
// MyEnum | |
export type MyEnumValue = EnumValue<typeof MyEnum>; | |
export type MyEnumKey = EnumKey<typeof MyEnum>; | |
export const MyEnum = { | |
KeyA: 1, | |
KeyB: 2, | |
} as const; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment