-
|
Is there a way to compare between For example: const a = z.nullable(z.object({ id: z.string() }));
const b = z.object({ id: z.string() });
isSameType(a, b); // false
isSuperType(a, b); // true
isSameType(z.object({ id: z.string() }, z.object({ id: z.string() }); // true
// A simple impl
function isSameType(a: ZodTypeAny, b: ZodTypeAny): boolean {
if (a._def.typeName !== b._def.typeName) return false;
if (a.isOptional() !== b.isOptional()) return false;
if (a.isNullable() !== b.isNullable()) return false;
if (a instanceof z.ZodObject) {
if (!(b instanceof z.ZodObject)) {
return false;
}
const aShape = a.shape;
const bShape = b.shape;
if (Object.keys(aShape).length !== Object.keys(bShape).length) return false;
for (const key in aShape) {
if (!(key in bShape)) return false;
if (!isSameType(aShape[key], bShape[key])) return false;
}
}
// TODO many edge cases
return true;
};
// How can I implement this?
function isMatch(fn: ZodTypeFunction, args: ZodTuple): boolean {
// ...
};
function isSuperType(super: ZodTypeAny, sub: ZodTypeAny): boolean {
// ...
}; |
Beta Was this translation helpful? Give feedback.
Answered by
lawvs
Mar 1, 2024
Replies: 1 comment 1 reply
-
|
To solve this problem, I developed a new package called zod-compare, which provides functions for comparing Zod schemas to determine whether two schemas are equal or compatible. import { z } from "zod";
import { isSameType, isCompatibleType } from "zod-compare";
isSameType(z.string(), z.string()); // true
isSameType(z.string(), z.number()); // false
isSameType(
z.object({ name: z.string(), other: z.number() }),
z.object({ name: z.string() }),
);
// false
isCompatibleType(
z.object({ name: z.string(), other: z.number() }),
z.object({ name: z.string() }),
);
// true |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
JacobWeisenburger
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To solve this problem, I developed a new package called zod-compare, which provides functions for comparing Zod schemas to determine whether two schemas are equal or compatible.