-
Hello, how create zodtype with object props from external types? // Generated type from API
type User = {
id: number
name: string
}
const UserSchema = z.ZodType<User> = z.object({
id: z.number(),
name: z.string()
})
UserSchema.pick // not working
// Property 'pick' does not exist on type 'ZodType<User, ZodTypeDef, User>'. |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments 1 reply
-
type User = {
id: number;
name: string;
};
const UserSchema = z.object({
id: z.number(),
name: z.string(),
});
type USER = z.infer<typeof UserSchema>;
|
Beta Was this translation helpful? Give feedback.
-
Maybe you are looking to construct a validation object ( // Generated type from API
type User = {
id: number;
name: string;
};
const UserSchema: z.ZodObject<any, any, any, User> = z.object({
id: z.number(),
name: z.string(),
});
UserSchema.pick; // now it works |
Beta Was this translation helpful? Give feedback.
-
Modern solution TS 4.9+ type User = {
id: number
name: string
age: number
}
const UserSchema = z.object({
id: z.number(),
name: z.string(),
age: z.number()
}) satisfies z.ZodType<User> |
Beta Was this translation helpful? Give feedback.
-
@domosedov thanks for this. While it helps a lot, it fails at :
|
Beta Was this translation helpful? Give feedback.
-
This solution is really helpful, but I wish it forwarded JSDoc information. That may be way out of scope, if so I apologize. Here are a couple images illustrating what I mean (check out where the cursor is) Property description Zod parse with satisfies type... no description :( |
Beta Was this translation helpful? Give feedback.
-
i just end up using this implementation since i only want the keys for intellecence while adding validation so i get types from db scheam or gql generate or other then based on that i validate so it's fine for my usecase. export type InferZodMap<T extends abstract new (...args: any) => any> = {
[k in keyof Partial<InstanceType<T>>]?: unknown;
};
// then use it in zod
type User {
email: string;
}
const UserInsertValidation = z.object({
email: z.string(),
} satisfies InferZodMap<typeof User>); this one doesn't seem to work form me const UserInsertValidation = z.object({
email: z.string(),
}) satisfies ZodType<User>; |
Beta Was this translation helpful? Give feedback.
Modern solution TS 4.9+