T
TanStack2mo ago
extended-salmon

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.
// FormPage

const validationSchema = z.object({
name: z.string().min(1, 'Name required'),
});

const formOpts = formOptions({
defaultValues: {
name: obj.name || '',
},
validators: {
onChange: validationSchema,
},
});

const form = useAppForm({...});
// FormPage

const validationSchema = z.object({
name: z.string().min(1, 'Name required'),
});

const formOpts = formOptions({
defaultValues: {
name: obj.name || '',
},
validators: {
onChange: validationSchema,
},
});

const form = useAppForm({...});
//TextField

const field = useFieldContext<string>();

const errors = useStore(field.store, (state) => state.meta.errors);

// the real type of errors is :
// {
// expected: string,
// code: string,
// path: string[],
// message: string
// }[]
//
// it's actually the issues property in ZodError
//TextField

const field = useFieldContext<string>();

const errors = useStore(field.store, (state) => state.meta.errors);

// the real type of errors is :
// {
// expected: string,
// code: string,
// path: string[],
// message: string
// }[]
//
// it's actually the issues property in ZodError
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
harsh-harlequin2mo 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 string
extended-salmon
extended-salmonOP2mo 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
harsh-harlequin2mo ago
well, yeah
extended-salmon
extended-salmonOP2mo ago
Thanks

Did you find this page helpful?