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.
Created
September 5, 2023 14:36
-
-
Save shcallaway/84574d11017c3de762945b7808ccc45d to your computer and use it in GitHub Desktop.
Compare Zod schemas for equality
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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