I love the Zod parser but I may have gotten in over my head creating a form lib.
In the ideal end state, the input shape is transformed to create { fieldA: { value, onChange, errors } }
. It works for a single level, but it's not clear how to support arrays and nested objects.
Can typescript transform recursive generics like this?
Zod represents parsers like this:
const schema = z
.object({
name: z.string().min(3, 'Too short.'),
nested: z.object({
name: z.string(),
}),
repeat: z.array(z.object({
arrNest: z.string(),
})),
}).transform((v) => v.name);
Then using type inference:
const example = <Input extends { [v: string]: any }, Output extends unknown>(
schema: z.ZodType<Output, any, Input>
) => {
type Fields = {
[P in keyof Input]: {
value: Input[P];
};
};
return ({} as unknown) as Fields;
};
export const typed = example(schema);
Name has the desired type { value: string }
but repeat has:
Instead, I want to apply this recursively with Objects and Arrays
Then types.repeat
would have type { arrNest: { value: string } }[]
Notes
The zod object type is rather complicated..
but I am only concerned with the Input
, represented as
export type ZodRawShape = { [k: string]: ZodTypeAny };