zod icon indicating copy to clipboard operation
zod copied to clipboard

Please add TypeScript support for `.extend()` method in the z.Schema type

Open ArsenBatyuchok opened this issue 2 years ago • 4 comments

I find it very useful to add my types for Zod schemas, so that if I change the type, TypeScript helps me in highlighting the errors in my broken schemas. But as soon as I assign any schema z.Schema<MyType>, I can no longer extend this schema. Here's a detailed example:

  1. Without z.Schema<MyType> specification:
const mySchema = z.object({ ... });
const anotherSchema = mySchema.extend({ ... });

Works just fine, but no highlights if I have my types mismatched with the schema.

  1. With z.Schema<MyType> specification:
const mySchema: z.Schema<MyType> = z.object({ ... });
const anotherSchema = mySchema.extend({ ... });

Here, I have my type definitions connected to Zod schemas, but I can no longer safely extend from mySchema (by safely, I mean type-safety, if I put @ts-ignore, it works just as expected).

Please suggest a workaround if any exists or add a type support for extend method in Schema type definition. Thanks!

ArsenBatyuchok avatar Jul 20 '22 16:07 ArsenBatyuchok

can't agree more,I asked the question too。https://github.com/colinhacks/zod/issues/1271

UNDERCOVERj avatar Jul 24 '22 03:07 UNDERCOVERj

You can do this using const anotherSchema:z.Schema<AnotherType> = mySchema.and(z.object({ ... }));

CoolColdUK avatar Jul 28 '22 22:07 CoolColdUK

Also for z.ZodType

Profesor08 avatar Sep 22 '22 14:09 Profesor08

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Nov 21 '22 19:11 stale[bot]