How to understand z.infer and type of in these statements?
#5344
-
They both look like fetching the type. I do not know why not using either of them immediatelly. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
Great question! In TypeScript,
You need both: To reply, just mention @dosu. How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other |
Beta Was this translation helpful? Give feedback.
Great question! In TypeScript,
typeof LexiconsSchemagives you the type of the schema object itself (i.e., the Zod schema instance), not the type of the data it validates.z.infer<typeof LexiconsSchema>is a Zod utility that extracts the TypeScript type of the data that would successfully pass validation by your schema. So in your example,Lexiconswill be the type of the validated data (likeMap<string, LexiconDetail>), not the schema object.You need both:
typeofto reference the schema, andz.inferto get the validated data type. This pattern is standard in Zod and lets you keep your runtime validation and static typing in sync. More details and examples are in the Zod docs.To reply,…