Is it possible to generate schema from object literal? #3933
Unanswered
Gumichocopengin8
asked this question in
Q&A
Replies: 1 comment 1 reply
-
Could you dynamically build your schema based on the object? Something like this (untested): const OBJ_LITERAL_ARRAY = [
{ name: 'name1', text: 'Text1' },
{ name: 'name'2, text: 'Text2' },
// ... 1,000 more
{ name: 'nameN', text: 'TextN' },
] as const;
const zodObjects = OBJ_LITERAL_ARRAY.map((obj) => {
return z.object({
text: z.literal(obj.text),
name: z.literal(obj.name),
});
});
const OBJ_LITERAL_ARRAY_SCHEMA = z.array(z.union(zodObjects)); Alternatively, you could do something like (untested): const OBJ_LITERAL_ARRAY_SCHEMA = z.array(
z.object(
text: z.string(),
name: z.string(),
),
).superRefine((data, ctx) => {
for (let i = 0; i < data.length; i++) {
// If there's a pattern to name/text, you could calculate the expected value instead of comparing to OBJ_LITERAL_ARRAY
if (data[0].text !== OBJ_LITERAL_ARRAY[i].text) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: `Index ${i} text is invalid.` });
}
if (data[0].name !== OBJ_LITERAL_ARRAY[i].name) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: `Index ${i} name is invalid.` });
}
}
}); |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have an object literal like this.
It is painful to construct zod schema by hand.
Are there any ways to generate zod schema from the object literal like the following??
Beta Was this translation helpful? Give feedback.
All reactions