For maximum reusability, create a custom hook:
function useNestedFieldError(error: FieldError | undefined, fieldName: string) {
if (!error) return undefined;
if (error.type === "required") return error;
return (error as any)[fieldName] as FieldError | undefined;
}
// Usage in component:
const xError = useNestedFieldError(fieldState.error, "x");
The cleanest solution would be to properly type your form errors from the beginning. When setting up your form, you can provide a generic type that includes the nested structure:
type FormValues = {
vector: Vector3D;
};
const { formState: { errors } } = useForm<FormValues>();
// Now errors.vector will be properly typed as Vector3DError
This way, TypeScript will understand the nested error structure throughout your application.
I have learned a lot throughout this challenge.
I hope this answer will help you.
Best Regards,
Tyler