Is it possible to dynamically generate zod schema?

Imagine a form where a user can add/remove fields of different types, how can we dynamically generate zod schema for that form?
7 Replies
Neto
Neto2y ago
generate the basic zod structure such as z.string() then merge them probably its just impossible the get the correct type later
shikishikichangchang
what do you mean
Neto
Neto2y ago
GitHub
TypeScript-first schema validation with static type inference
TypeScript-first schema validation with static type inference
Neto
Neto2y ago
const input = {elem1: 'string', elem2: 'string'}

const getZodElem = (t: string) => {
if (t === 'string') {
return z.string()
}
...
}

// map input into zod schema
const input = {elem1: 'string', elem2: 'string'}

const getZodElem = (t: string) => {
if (t === 'string') {
return z.string()
}
...
}

// map input into zod schema
shikishikichangchang
ok let me try that thank you so much!
Pijus
Pijus16mo ago
@shikishikichangchang what was final solution that you did? I've started gathering ideas today, wondering if there is any clean implementation
Tomate Malicioso
Tomate Malicioso15mo ago
You can generate the zod validator but you can't infer the type from it , as it'd be done on runtime and not during the TypeScript compilation step. If I understand the implications correctly, you can't pick the type from the generated validator and, for example, have it as an argument or return type from another function. But you can definitely validate around using your dynamically generated zod validator.
Want results from more Discord servers?
Add your server