colinhacks / zod

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

Please adhere to SemVer #2851

Open james-yeoman opened 1 year ago

james-yeoman commented 1 year ago

I started using zod in one of the packages in my team's monorepo, and everything was great. The zod version that Yarn installed was v3.22.2.

I then add zod to another package in my team's monorepo and it's still great. At this point, v3.22.4 is released, and Yarn chooses to install that version.

I then import a zod schema from the first package into the second package, try to use it to create a new schema, and the typescript server freaked out.

Here's an exerpt from my tsserver.log (manually prettified)

Info 1066 [10:56:04.300] event:
{
    "seq":0,
    "type":"event",
    "event":"semanticDiag",
    "body":{
        "file":"/<my team's monorepo>/packages/api/src/types/root.schema.ts",
        "diagnostics":[{
            "start": { "line": 116, "offset": 28 },
            "end": { "line": 122, "offset": 3 },
            "text": "Type instantiation is excessively deep and possibly infinite.",
            "code": 2589,
            "category": "error"
        }, {
            "start": { "line": 116, "offset": 14 },
            "end": { "line": 116, "offset": 25 },
            "text": "The inferred type of 'Declaration' cannot be named without a reference to '@lll/shared/node_modules/zod'. This is likely not portable. A type annotation is necessary.",
            "code": 2742,
            "category": "error"
        }]
    }
}

where Declaration is the schema I was constructing in root.schema.ts, using an import from @lll/shared.

It's worth noting, that error appeared only when adding a field to the object schema that used a schema from @lll/shared.

import { Schemas } from "@lll/shared";

//...

export const RootType = z.object({
//...
});

//...

export const Declaration = RootType.extend({
    // Inline schema properties. No dependency on @lll/shared
    //...

    allergens: Schemas.Primative.Allergens
});
mmayla commented 12 months ago

I have exactly the same issue, did you find a way to fix it?

james-yeoman commented 12 months ago

I pinned the version of zod across my monorepo using the resolutions map in the root package json

james-yeoman commented 12 months ago

E.g.

// <repo root>/package.json
{
  //...
  "resolutions": {
    "zod": "^3.x.x"
  }
}

// <repo root>/packages/api/package.json
{
  //...
  "dependencies": {
    //...
    "zod": "*"
  }
}

// <repo root>/packages/shared/package.json
{
  //...
  "dependencies": {
    //...
    "zod": "*"
  }
}

which ensured everything, including dependencies that use zod, use the most up-to-date, same version. You could always pin the zod version to a specific one if you needed to