As much as I adore the Zod parser, I fear I may have bitten off more than I can chew with my form library.
In an ideal scenario, the input structure would be transformed to create
{ fieldA: { value, onChange, errors } }
. While this works well for a single level, it becomes unclear how to handle arrays and nested objects.
I wonder if TypeScript is capable of transforming recursive generics in a similar manner?
Zod embodies parsers like so:
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);
By leveraging 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);
The 'name' now possesses the desired type of { value: string }
, however, 'repeat' raises concerns:
https://i.sstatic.net/caN4a.png
My aim is to recursively implement this concept with Objects and Arrays
Hence, types.repeat
should hold the type { arrNest: { value: string } }[]
Notes
The Zod object type is quite intricate..
Nevertheless, my focus lies solely on the Input
, which is represented as:
export type ZodRawShape = { [k: string]: ZodTypeAny };