Morning everybody ๐
I'm looking for a substitution for enums and so far I'm stuck with this pattern:
export const MyEnumSchema = z.enum({ A: 0, B: 2 /*...*/ });
export const MyEnum = MyEnumSchema.enum;
export type MyEnum = z.infer<typeof MyEnumSchema>;
To reduce boilerplate, I wrote a helper that returns all three values and types:
type EnumLike = Readonly<Record<string, string | number>>;
function e<const T extends EnumLike>(map: T) {
const schema = z.enum<T>(map);
return {
schema,
enum: schema.enum,
Type: null as unknown as z.infer<typeof schema>,
};
}
But I can't find a way to destructure the type cleanly on the other side:
export const {
schema: ExampleEnumSchema,
enum: ExampleEnum,
// Type: ExampleEnum,
} = e({ A: 1, B: 2 });
Any thoughts on a pattern that avoids the boilerplate while still getting schema + runtime enum + inferred type?