T
TanStack2w ago
foreign-sapphire

Validation error type safety when using form composition

Is there any way to pass a type down for validation errors when using form composition? Looks like it comes back as any through useFieldContext, but for instance I know I'll always use Zod and so it should always be a ZodError in my case
3 Replies
like-gold
like-gold2w ago
when using field context, the error can actually be anything. If you want to pass it in a type safe way, pass it as prop from the field callback from <form.AppField>
foreign-sapphire
foreign-sapphireOP2w ago
I get what you're saying; I'll be sacrificing type safety instead, because I don't want to pass it in for every field I'm just going to use as in my custom components, I just thought maybe one of the generics was it and I just didn't know how to pass it in ha
like-gold
like-gold2w ago
unless you need zod-specific properties, you can narrow it with a small function just fine
function isNotNil<T>(value: T): value is NonNullable<T> {
return value !== null && typeof value !== 'undefined';
}

function tryGetErrorMessage(errors: unknown[]): string | null {
// valid errors, sorted by priority:
// | string -> string
// | undefined | null -> null
// | { message: unknown } ->
// error.message
// | string -> string
// | null | undefined -> null
// | -> String(error.message)
// | -> String(error)

const error = errors.find(isNotNil);
if (!error) {
return null;
}

if (typeof error === 'string') {
return error;
}

if (typeof error === 'object' && 'message' in error) {
if (error.message === null || error.message === undefined) {
return null;
} else if (typeof error.message === 'string') {
return error.message;
} else {
return String(error.message);
}
}

return String(error);
}
function isNotNil<T>(value: T): value is NonNullable<T> {
return value !== null && typeof value !== 'undefined';
}

function tryGetErrorMessage(errors: unknown[]): string | null {
// valid errors, sorted by priority:
// | string -> string
// | undefined | null -> null
// | { message: unknown } ->
// error.message
// | string -> string
// | null | undefined -> null
// | -> String(error.message)
// | -> String(error)

const error = errors.find(isNotNil);
if (!error) {
return null;
}

if (typeof error === 'string') {
return error;
}

if (typeof error === 'object' && 'message' in error) {
if (error.message === null || error.message === undefined) {
return null;
} else if (typeof error.message === 'string') {
return error.message;
} else {
return String(error.message);
}
}

return String(error);
}

Did you find this page helpful?