Skip to content

Instantly share code, notes, and snippets.

@larvanitis
Created July 26, 2023 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save larvanitis/3f8e37845fc8b612021d3d8492c85245 to your computer and use it in GitHub Desktop.
Save larvanitis/3f8e37845fc8b612021d3d8492c85245 to your computer and use it in GitHub Desktop.
TypeScript enum-like objects and util functions
// 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