colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.09k stars 1.15k forks source link

Property 'pick' does not exist on type 'ZodType<Output, ZodTypeDef, Input>'. #3645

Open dugip opened 2 months ago

dugip commented 2 months ago

Found a related issue here: https://github.com/colinhacks/zod/issues/2403 - but it doesn't provide a proper solution

I have a zod schema that uses .lazy and needs explicit typing with z.ZodType<Output, z.ZodTypeDef, Input>. All is well in that regard and that works, but considering that the schema is an object, I'm losing some typing here when I try to .pick from my explicitly typed schema.

Is there an alternative to z.ZodType that can be used on object schemas, such that pick and omit remain available and no types are lost?

Example code:

const nested = z.object({
  bar: z.string(),
}).transform((data) => {
  // transform...
});

const base = z.object({
  foo: z.string(),
}).transform((data) => {
  // transform...
});

type Input = z.input<typeof base> & { nestedObj: z.input<typeof nested> }
type Output = z.output<typeof base> & { nestedObj: z.infer<typeof nested> }

const extendedBase: z.ZodType<Output, z.ZodTypeDef, Input> = base.extend({
  nestedObj: z.lazy(() => nested.optional())
});

const derivedFromExtendedBase = extendedBase.pick({
  foo: true
});

// ^ Property 'pick' does not exist on type 'ZodType<Output, ZodTypeDef, Input>'.

Essentially, I'm looking for an alternative to z.ZodType. Perhaps z.ZodObjectType<TOutput, TTypeDef, TInput>?

dugip commented 1 month ago

Bump