colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.09k stars 1.15k forks source link

Misleading Error: "Property 'infer' Does Not Exist" When Using const Instead of type in Zod #3687

Closed Mandeep56Singh closed 1 month ago

Mandeep56Singh commented 1 month ago

I got the Typescript error:

Property 'infer' does not exist on type 'typeof import(.../node_modules/zod/lib/external)

const CampaignForm = z.infer<typeof CampaignSchema>;

Looking at the docs and node_modules the property is there.

The issue was using const instead of type.

Expected: type CampaignForm = z.infer<typeof CampaignSchema>;

Actual: const CampaignForm = z.infer<typeof CampaignSchema>;

The error is misleading.

although i have this issue but for sake of clearity i have copy pasted from stack overflow here is the link stack overflow question on this issue

median-dxz commented 1 month ago

The Infer method is a type helper that you should only use it in a type declaration rather than a const declaration. You can regard it as a "function" that make ts type from a zod schema object and it should not exist in actual js code.

Mandeep56Singh commented 1 month ago

@median-dxz I know that , but the message in error is misleading , it questions your whole installation of zod. When this error occured i didn't look at const or type because of misleading error message. I don't thing it's good experience for new commers and the error message is incorrect infer do exist but not on const.

median-dxz commented 1 month ago

@Mandeep56Singh OK, I get your point now. Sorry for misunderstanding before. But at least for me, I may not think the error message is misleading. Firstly, it's clearly claim that "infer" is not a property in the namespace "z". Secondly, after all, it's a typescript error that zod cannot affect how it will be displayed.

Mandeep56Singh commented 1 month ago

@median-dxz, sorry for the late reply. I'm not the only one encountering this problem; it's a common issue on Stack Overflow. Here's the link: Stack Overflow question on this issue.

To be honest, I agree with you that this is a small issue and can be ignored. However, my point is that the error message should accurately point to the error, not mislead. As the message currently states, "Zod - Property 'infer' does not exist on type 'typeof import(.../node_modules/zod/lib/external)", many developers might think that infer doesn't exist, as reflected in the votes on the Stack Overflow question.