colinhacks / zod

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

Bug: Defining schema shape causes a TS error when it shouldn't #3724

Closed lounging-lizard closed 3 weeks ago

lounging-lizard commented 3 weeks ago

Description

When defining the schema shape using a type (const Schema: z.ZodType<MyType> = ...) Typescript is raises an error when using a schema and the pipe method.

I believe it to be a bug as the correct type is inferred from the schema.

Example

Zod Version 3.23.8

import { z } from "zod";

export const StringListSchema = z.string().transform((input) => input?.split(","));

export type InputType = {
  strings?: string[];
};

const Schema: z.ZodType<InputType> = z.object({
  strings: StringListSchema.pipe(z.array(z.string())).optional(),
});
// Type Error: Type 'string | undefined' is not assignable to type 'string[] | undefined'.

export type OutputType = z.infer<typeof Schema>;
// Infered Type: type OutputType = { strings?: string[] | undefined; }

console.log(Schema.parse({ strings: "one,two" }));
// Output: { strings: [ 'one', 'two' ] }
lounging-lizard commented 3 weeks ago

My apologies, I had not noticed that the inferred input type was in fact the issue, and the bug was due to my misunderstanding.

If anybody comes across this it is because the input component of z.ZodType is inferred from the output component of the generic.