My goal is to create a function that validates an object against a Zod schema in TypeScript. However, I have encountered an issue where TypeScript does not seem to properly validate the object when using a spread operator.
In the scenario below, the function myTestFunc
expects a schema
of any Zod schema type and a newItem
that corresponds to the inferred type from the schema
. TypeScript correctly flags an error when passing an object with an additional property like city: "Paris"
. However, when using the spread operator ...{city: "Paris"}
, TypeScript does not catch the error and allows it to pass through.
import { z } from "zod";
const myTestFunc = <U extends z.AnyZodObject>(
schema: U,
newItem: z.infer<U>,
) => {
console.log("some processing here");
};
const schemaA = z.object({
name: z.string(),
age: z.number(),
});
myTestFunc(schemaA, {
name: "John",
age: 25,
city: "Paris", // <- error, as "city" is not an allowed part of the type
});
myTestFunc(schemaA, {
name: "John",
age: 25,
...{city: "Paris"}, // <- no error, so weird
});
This inconsistency with TypeScript validation is frustrating, especially when working with generic Zod objects.
I also attempted a different approach to address the issue:
import { z } from "zod";
type MyTestFuncParams<U extends z.AnyZodObject> = {
schema: U;
newItem: z.infer<U>;
}
const myTestFunc = <U extends z.AnyZodObject>(
{schema,
newItem}: MyTestFuncParams<U>,
) => {
console.log("some processing here");
};
const schemaA = z.object({
name: z.string(),
age: z.number(),
});
const brokenItem = {
name: "John",
age: 25,
city: "Paris",
};
myTestFunc({schema: schemaA, newItem: brokenItem}); // <- no error!
Here is what TypeScript is expecting
Here are the actual item contents
The lack of type error in this scenario is baffling. My IDE (VSCode) clearly indicates a type mismatch.
I am seeking guidance on how to modify the function to ensure proper type validation. Any assistance would be greatly appreciated!