is casting with `as` after a zod parse normal or am i doing types wrong Inference
Six months into TypeScript, coming from JS. I parse a request body with zod and then write const input = schema.parse(body) as CreateUserInput because the hover tooltip on the parse result is an unreadable wall of ZodObject<{...}> and I already have a CreateUserInput interface defined for the rest of the app.
It compiles, it works, but it feels like I am doing something the language is trying to stop me from doing. Is this a normal thing people do or is it a beginner smell?
@orm_tamsin · 8mo ago · 3 replies
It is a smell, and the specific thing it means is that you have two sources of truth for the same shape.
parse()already returns exactly the right type. Derive the interface from the schema instead of declaring it separately and casting to it:Now there is one definition. Change the schema and every consumer updates. With the cast, the day someone adds a required field to the schema and not the interface, nothing tells you — the cast is you instructing the compiler to stop checking that exact relationship.
On the unreadable tooltip: that is a display problem, not a type problem. The
ZodObject<...>wall is the schema's type;z.inferof it is a plain object type and hovers fine.Reply
Report
@headless_hugo · 8mo ago
The hover tooltip thing catches everyone. If you want readable hovers on any derived type:
Wrap and the tooltip flattens. Changes nothing at runtime and nothing about assignability, it just makes the editor tell you the truth in a readable way.
Reply
Report
@goldenhourgus · 8mo ago
One definition instead of two. I have been maintaining both by hand for six months and had genuinely not made the connection that the cast was the thing letting them drift.
Reply
Report