#"Parameterized" Zod schema

9 messages · Page 1 of 1 (latest)

urban lanternBOT
#
drwarpman#0

Preview:```ts
import {z} from "zod"

const schema = (id: string) =>
z.object({
[id]: z.any(),
})

// foobar is { [x: string]: any; }
const foobar = schema("abc").parse(null)

// How to get: { abc: any; } instead?```

#
nonspicyburrito#0

Preview:```ts
import {z} from "zod"

const schema = <T extends string>(id: T) =>
z.object({
[id]: z.any(),
}) as z.ZodObject<Record<T, z.ZodAny>>

const foobar = schema("abc").parse(null)
// ^?```

pseudo thunder
#

So the typecast is necessary?

pseudo thunder
# urban lantern

but this way, you'd have to type the value manually twice, z.ZodAny, what if the object was too big to copy the type?

dusky turret
#

I mean, you can just do:

const propertySchema = z.any()

const schema = <T extends string>(id: T) =>
    z.object({
        [id]: propertySchema,
    }) as z.ZodObject<Record<T, typeof propertySchema>>
pseudo thunder
#

yea. ok. thank u

dusky turret
#

You can also move the cast inside:

z.object({ [id]: propertySchema } as Record<T, typeof propertySchema>)
pseudo thunder
#

wait, what, what did u do 😄

dusky turret
#
z.object({ ... } as ...)
// vs
z.object({ ... }) as ...