Skip to content

Instantly share code, notes, and snippets.

@shcallaway
Created September 5, 2023 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shcallaway/84574d11017c3de762945b7808ccc45d to your computer and use it in GitHub Desktop.
Save shcallaway/84574d11017c3de762945b7808ccc45d to your computer and use it in GitHub Desktop.
Compare Zod schemas for equality

This is a naive way of comparing two Zod schemas to see if they are equivalent. Basically, it works by serializing the two schemas and comparing the resulting strings. This approach is limited because serialization doesn't capture all of the information about certain Zod types, e.g. functions.

const zod = require("zod");
const a = zod.object({
status: zod.enum([
"success",
"failure",
]),
response: zod.string(),
});
const b = zod.object({
status: zod.enum([
"success",
"failure",
]),
response: zod.string(),
});
const c = zod.object({
status: zod.enum([
"success",
]),
response: zod.string(),
});
const compareSchemas = (schema1, schema2) => {
return JSON.stringify(schema1.shape) === JSON.stringify(schema2.shape);
};
compareSchemas(a, b); // true
compareSchemas(a, c); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment