by Ezku · 6y ago · 0 comments
Looks useful - I would have an easier time introducing this than io-ts.
Here's the Zod equivalent:
const C = z.object({
foo: z.string(),
bar: z.number().optional(),
});
type C = t.TypeOf<typeof C>;
/* {
foo: string;
bar?: number | undefined
} */
And here's the code that pulls this off: type OptionalKeys<T extends z.ZodRawShape> = {
[k in keyof T]: undefined extends T[k]['_type'] ? k : never;
}[keyof T];
type RequiredKeys<T extends z.ZodRawShape> = Exclude<keyof T, OptionalKeys<T>>;
type ObjectType<T extends z.ZodRawShape> = {
[k in OptionalKeys<T>]?: T[k]['_type'];
} &
{ [k in RequiredKeys<T>]: T[k]['_type'] };
export class ZodObject<T extends z.ZodRawShape> extends z.ZodType<
ObjectType<T>, // { [k in keyof T]: T[k]['_type'] },
ZodObjectDef<T>
>{
// ...
}FWIW it’s made my life easier to say the keys will always be there, but the values are possibly undefined. Less room for ambiguous interpretation.
It's definitely possible to wrap `io-ts` to get a better interface, especially if you spend some (or rather, a LOT) of time figuring out the type declarations...