Reverse type inference #3253
-
First of all, I really love Zod! I tried a few validation libraries and Zod by far clicked with me the most. I especially love the TypeScript integration and how easy it is to create a pair of type/interface and validator (schema). I think it would be amazing if (I'm not sure if this is implemented yet, I haven't found something similar) it would be possible to to reverse type inference. Something like this: interface MyType {
firstName: string
lastName: string
age: number
whatever?: boolean
}
const myTypeSchema = z.fromType<MyType>({
firstName: z.string(),
// error: lastName is missing
age: z.string(), // error: invalid type
extra: z.number() // error: extra
}) This would make using the library much easier if you already have a bunch of existing interfaces, especially if you cannot modify them. Basically, an equivalent of I currently use this pretty bad hack because I will never understand types in TypeScript, why are they even turning complete: ({} as MyType) satisfies z.infer<typeof myTypeSchema>
({} as z.infer<typeof myTypeSchema>) satisfies MyType This throws type errors if the schema isn't defined correctly. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Is this what you are looking for? interface MyType {
firstName: string
lastName: string
age: number
whatever?: boolean
}
const myTypeSchema = z.object( {
firstName: z.string(),
lastName: z.string(),
age: z.number(),
extra: z.number(),
} ) satisfies z.Schema<MyType> If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 |
Beta Was this translation helpful? Give feedback.
Is this what you are looking for?
If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏
https://github.com/sponsors/JacobWeisenburger