Using Zod with Javascript, how do I change the value of a single prop in my Zod object while still taking advantage of validation?
Examples (vanilla JS):
import * as z from 'zod';
const MyObjectSchema = z.strictObject({
prop1: z.number().gte(5), // Any number >= 5.
prop2: z.string(), // Any string.
prop3: z.array(z.number()) // Array of any numbers.
});
// The following executes with no errors, and sets the props as specified.
const myThing = MyObjectSchema.parse({
prop1: 99,
prop2: 'Slartibartfast',
prop3: [1, 43, 1]
});
// The following is legal, with no error thrown, despite the "gte(5)" above;
// because this assignment doesn't use Zod's parse() for validation.
myThing.prop1 = 1;
// The following throws an error, because Zod's parse() wants the entire object
// submitted, not a single prop.
myThing = MyObjectSchema.parse({ prop1: 40 });
My searching suggests that I need to parse the entire object every time I want to change a single prop, if I want validation; or else write wrapper functions. Can this be true? Am I a uniquely bad programmer who just wants to do myObject.prop2 = 4; without having to set the 100 properties of my big object? TIA.
You can use destructuring and then set whatever you want to a new value:
myThing = MyObjectSchema.parse({ ...myThing, prop1: 40 });
This also works in case of multiple new values, just put them all after each other, with a comma in between.