Z
Zod15mo ago
Scott Trinh

Do you mean dynamically create an

Do you mean dynamically create an arbitrary schema at runtime based on the shape of one object and then compare a second object using that dynamically generated schema? It's possible, although it will be quite difficult if you plan on support anything other than primitives (string, number, boolean, null, array, object, etc). Even object vs. record will be hard to infer at runtime without some guidance.
4 Replies
Unknown User
Unknown User15mo ago
Message Not Public
Sign In & Join Server To View
Scott Trinh
Scott TrinhOP15mo ago
If the object is all one level, you can loop over main object, and build a z.object dynamically. Something like:
import { z } from "zod";

const mainPalette = {
foo: "bar",
baz: 12,
};

const paletteSchema = Object.entries(mainPalette).reduce(
(schema, [key, val]) => {
const valSchema =
typeof val === "string"
? z.string()
: typeof val === "number"
? z.number()
: z.unknown();
return schema.extend({
[key]: valSchema,
});
},
z.object({}),
);
import { z } from "zod";

const mainPalette = {
foo: "bar",
baz: 12,
};

const paletteSchema = Object.entries(mainPalette).reduce(
(schema, [key, val]) => {
const valSchema =
typeof val === "string"
? z.string()
: typeof val === "number"
? z.number()
: z.unknown();
return schema.extend({
[key]: valSchema,
});
},
z.object({}),
);
https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAbzgLzgXzgMyhEcBEyEAJvgNwBQFAxhAHYDO8IAhsHQAosA2ApjDF5wAvIgpwsECAC4CAIxZR8AGnFwFyWQEYATKrSUa9JnDA9+ggMrUAFr1Yi4AeTkArXtRgA6XnRhRgXgYAClZ2Lj4BXgBKLyheYgBXal5gtWCGW3sWZTgAbQBrXgBPXIA3HgBdaJEAPjEJCVpGeAruazsHYTVGuBhisF4ITDg2kWFRfCYAugBzfB7euAB+FC9p9lng6MXe2X7B4dGeccm6RJA5XiVdxtXkL3PL6+3biVkHxLoCuggAdzo20ovXiMESUDocEynRYPgAHoI6MRgghboUSpVZG0OtlVL00NFgeg8WsIG4PDAUQTVISKEA
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
Unknown User
Unknown User15mo ago
Message Not Public
Sign In & Join Server To View
Scott Trinh
Scott TrinhOP15mo ago
Yeah, I'd say Zod is pretty focused on matching compile-time behavior to a runtime, so since this is entirely runtime and dynamic, it's a little awkward to do it in Zod. Definitely doable, but just not really a target use case. There might be more dynamic validation/parsing libraries (especially from the JS ecosystem?) that might make this a bit easier, but if you're already using Zod in other places, makes sense to bend Zod around a bit.
Want results from more Discord servers?
Add your server