I desperately tried to generate a zod schema dynamically without success.
I have coded a kind of reusable form with react-hook-form, allowing me to easily create forms with various number of inputs. This component needs an array of fields, containing all the needed information to create them (type, label, classname, etc...).
In order to provide my form the right types I need to provide it my fields type to theuseForm<FieldValues>()
method. That's why I need to create a schema dynamically.
// Schema manually coded
const schema = z.object({
foo: z.string(),
bar: z.number()
})
type Fields = z.infer<typeof schema>
// { foo: string; bar: number; }
// Schema dynamically generated
const fields = [
{
name: "foo",
fieldType: z.string(),
//...
},
{
name: "bar",
fieldType: z.number(),
//...
}
]
const generateSchemaFromFields = (fields) => {
// ?
}
const generatedSchema = generateSchemaFromFields(fields)
type GeneratedFields = z.infer<typeof generatedSchema>
// { foo: string; bar: number; }
Any idea? Thanks in advance!
edit: I rewrote the question for clarity
z.object
is called withRecord<string, ZodTypeAny>
, and that means all schemas are consider asZodTypeAny
no matter what it was, to solve this will use lots of generic to keep the type information. And my personal suggestion is use object instead of array to store the schema in this case, it will be easier to inference the type – Crat