Is it possible to pass a zod schema as a prop?

I have this
interface Props {
schema: ZodSchema;
children: React.ReactNode;
defaultValues?: unknown;
}
interface Props {
schema: ZodSchema;
children: React.ReactNode;
defaultValues?: unknown;
}
what is the proper way to type the schema prop on the receiving end?
Solution:
owo7 if you want to accept any zod schema then you could do something like ``` import type { ZodSchema } from "zod" type ComponentProps<TSchema extends ZodSchema> = {...
Jump to solution
5 Replies
Solution
ja_iy
ja_iy2y ago
owo7 if you want to accept any zod schema then you could do something like
import type { ZodSchema } from "zod"

type ComponentProps<TSchema extends ZodSchema> = {
schema: TSchema,
children: React.ReactNode
}
function Component<TSchema extends ZodSchema>({schema, children}:ComponentProps<TSchema>){
return <>{children}</>
}
import type { ZodSchema } from "zod"

type ComponentProps<TSchema extends ZodSchema> = {
schema: TSchema,
children: React.ReactNode
}
function Component<TSchema extends ZodSchema>({schema, children}:ComponentProps<TSchema>){
return <>{children}</>
}
But if want to accept a specific schema
const schemaIn = z.object({
foo: z.literal('bar')
})

type ComponentProps = {
schema: typeof schemaIn,
children: React.ReactNode
}
function Component({schema, children}:ComponentProps){
return <>{children}</>
}
const schemaIn = z.object({
foo: z.literal('bar')
})

type ComponentProps = {
schema: typeof schemaIn,
children: React.ReactNode
}
function Component({schema, children}:ComponentProps){
return <>{children}</>
}
janusqa
janusqaOP2y ago
Thank you that helps.
ja_iy
ja_iy2y ago
np : D
mrnicericee
mrnicericee2y ago
The zod docs covers this, https://zod.dev/ Scroll down until you get to the z.infer. There’s another section that goes a bit more in depth, z.infer, z.input & z.output
GitHub
TypeScript-first schema validation with static type inference
TypeScript-first schema validation with static type inference
janusqa
janusqaOP2y ago
@MrNiceRicee (reads docs) thank you.
Want results from more Discord servers?
Add your server