0

when calling the pick method of a zodObject in a function by passing in a reference, how to set the type of T to ensure the correct type of return value?

function zodPickDemo<T extends ZodObject<ZodRawShape>>(src: T) {
  return src.pick({ id: true });
}

const dto = z.object({ id: z.string(), name: z.string() });
const picked = zodPickDemo(dto);
// In this case the type of picked is not the expected type

In the above code, the type expected to be obtained is a zodObject object type containing only the id, but what is obtained is a type such that:

z.ZodObject<Pick<z.ZodRawShape, never>, "strip", z.ZodTypeAny, {}, {}>

Playground: link

fu xiao
  • 13
  • 3

1 Answers1

0

Found this: https://github.com/colinhacks/zod/issues/567

For the time being, this is the way to handle it.

ZodObject<
  Pick<ReturnType<T["_def"]["shape"]>, 'id'>,
  T["_def"]["unknownKeys"],
  T["_def"]["catchall"]
>
fu xiao
  • 13
  • 3