zod: Exporting schemas from package breaks `instanceof`

When I export a schema from a package and use that schema in another package, the instanceof operator doesn’t work on ZodError or Schema. I’m also new to creating packages, so maybe there is something that I miss there!

How I’m using the exported schemas:

import { mySchema } from 'mylib';
import { z } from 'zod';

console.log(mySchema instanceof z.Schema); // false

try {
  mySchema.parse('');
} catch (error) {
  console.log(error instanceof z.ZodError); // false
}

// -----------------------------

const localSchema = z.object({});

console.log(localSchema instanceof z.Schema); // true

try {
  localSchema.parse('');
} catch (error) {
  console.log(error instanceof z.ZodError); // true
}

I have also created a demo project.

I call the package that I create schemas in mylib and the package that I’m using those, is called myprogram. I’m using npm link to add mylib to myprogram package. And also, I’m transpiling the mylib with npx tsc. Then you can test the code in myprogram with npx tsx index.ts.

A maybe related thing that I read about this. But I also checked that you are addressing this issue on ZodError class constructor.

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Reactions: 6
  • Comments: 16 (2 by maintainers)

Most upvoted comments

Oh wow. Embarrassingly I wasn’t aware of Symbol.hasInstance and it is such a game changer. I’ve seen multiple issues relating to dual package issues and for Zod 4 I was looking into a wat to partly avoid it (with an ESM wrapper that re-exports CJS, as recommended in the Node.js docs).

But of course there are always scenarios where multiple versions of Zod will be floating around.

In Zod 4 all schemas will have a kind property (e.g. kind = Symbol.for("ZodString")) and I’ll implement hasInstance with a simple symbol comparison.

Note to self (and hopefully others):
What fixed the problems for us was to import zod consistently like this: const {z} = require('zod'); instead of mixing imports with const z = require('zod');

Yeah, it took me a bit of searching for a solution before I found it. I also ran into it with one of our internal packages, which is why I had to find a solution. 😃

I had difficulty finding example implementations for my use case, but I store an object at a key in each instance of my class and in Symbol.hasInstance I check to see if that key exists, the key contains an object of the right shape, and the values in the shape are what I expect. If it is, I check that the return of this.getType() is what I expect it to be.

This can also happen even with a single zod installation, without iframes or anything, if one part of the code accesses the commonjs export (main in package.json) and another part accesses the esm export (module).

Issue in trpc-cli: https://github.com/mmkal/trpc-cli/issues/7

If anyone’s interested, a non-bullet-proof-but-in-most-cases-good-enough fix is to look at the constructor name as above, but you should also account for sub-classes:

export const looksLikeInstanceof = <T>(value: unknown, target: new (...args: any[]) => T): value is T => {
  let current = value?.constructor
  do {
    if (current?.name === target.name) return true
    current = Object.getPrototypeOf(current) as Function
  } while (current?.name)
  return false
}

PR in trpc-cli: https://github.com/mmkal/trpc-cli/pull/8

CC @colinhacks in case you know of some reason why the method above wouldn’t be a good idea for some reason. Given zod ships both commonjs and esm, so has the dual-package hazard, it would be nice if it used Symbol.hasInstance as @gtflip suggests to avoid this out of the box.

Also related: https://github.com/evanw/esbuild/issues/3333