colinhacks / zod

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

Documentation example for recursive types gives type error #3560

Open alligatorjazz opened 3 months ago

alligatorjazz commented 3 months ago

Issue

Type hints made for recursive types z.lazy( ... ) make all properties optional. I made a minimal reproducible example repo with the example of recursive types given in the documentation and this error is present.

Error Output

Type 'ZodObject<extendShape<{ name: ZodString; }, { subcategories: ZodLazy<ZodArray<ZodType<Category, ZodTypeDef, Category>, "many">>; }>, "strip", ZodTypeAny, { ...; }, { ...; }>' is not assignable to type 'ZodType<Category, ZodTypeDef, Category>'.
  Types of property '_type' are incompatible.
    Type '{ name?: string; subcategories?: Category[]; }' is not assignable to type 'Category'.
      Type '{ name?: string; subcategories?: Category[]; }' is not assignable to type '{ subcategories: Category[]; }'.
        Property 'subcategories' is optional in type '{ name?: string; subcategories?: Category[]; }' but required in type '{ subcategories: Category[]; }'. ts(2322)

tsconfig.json

{
    "compilerOptions": {
        "outDir": "dist",
        "declaration": true,
        "target": "ES6",
        "module": "CommonJS",
        "moduleResolution": "Node10"
    }
}

Example

https://github.com/alligatorjazz/recursive-error

lo1tuma commented 2 months ago

Looks like a duplicate of #2008. That’s being said, I can reproduce this issue.