Without z.infer, you must manually create the TypeScript type.
Without z.infer
import { z } from "zod";
const UserSchema = z.object({
name: z.string(),
age: z.number(),
});
type User = {
name: string;
age: number;
};
Notice that you're writing the same structure twice:
- Zod schema (for validation)
- TypeScript type (for type checking)
With z.infer
import { z } from "zod";
const UserSchema = z.object({
name: z.string(),
age: z.number(),
});
type User = z.infer<typeof UserSchema>;
Now you only write the structure once (in the schema), and TypeScript generates the type for you.
The problem without z.infer
Suppose you add an email field:
const UserSchema = z.object({
name: z.string(),
age: z.number(),
email: z.string(),
});
You must also remember to update:
type User = {
name: string;
age: number;
email: string;
};
If you forget, your schema and type become inconsistent.
So, without z.infer = manual type creation.
With z.infer = automatic type creation from the schema.
- Get link
- X
- Other Apps
- Get link
- X
- Other Apps
Comments
Post a Comment