Type of error object from useStore() using Zod
I would like to know how to tell TypeScript the type of the error object extracted from useStrore() using zod validation schema.
How can I make typescript know that this is the real type ? Is there a way to get it from Zod ?
4 Replies
harsh-harlequin•2mo ago
when using context, you assume that any form could be using your field. As consequence, errors could be of any type. So you have two approaches:
1. Pass errors as prop
In the field callback, errors will be typed. If you want to only accept zod error types, pass them as prop
2. Narrow unknown errors to strings
If you assume you only use field errors that are zod or strings, you can narrow it inside the field context by checking:
* For
typeof error === „string“
, and passing it directly if true
* Checking for typeof error === „object“ && error !== null && „message“ in error && typeof error.message === „string“
meaning a message property in an object which is a stringextended-salmonOP•2mo ago
Hi Luca. I understand what you mean. If I type errors as ZodError, my TextField would be barely reusable without Zod. Am I right ?
harsh-harlequin•2mo ago
well, yeah
extended-salmonOP•2mo ago
Thanks