T
TanStack5mo ago
blank-aquamarine

Search Param Zod Schema for array types with a single element?

Hi! I have a zod Schema that I'm using for my search params. Some of the properties I'm using are supposed to be arrays of strings. Ideally, the validation would be as simple as:
const processStringArraySchema = z.array(z.string())
const processStringArraySchema = z.array(z.string())
Everything is fine if the properties have multiple values inside them. However, when they have a single element the validation fails, telling me:
[
{
"code": "invalid_type",
"expected": "array",
"received": "string",
"path": [
"someProperty"
],
"message": "Expected array, received string"
}
]
[
{
"code": "invalid_type",
"expected": "array",
"received": "string",
"path": [
"someProperty"
],
"message": "Expected array, received string"
}
]
It seems it gets automatically converted to a string whenever someProperty has only one element inside it. So far the only solution I found was the following ugly schema, which I am not too confident about. I feel like these cases should be much easier to handle and that I'm probably missing something here:
const processStringArraySchema = z.preprocess(
(val) => (typeof val === 'string' ? [val] : val),
z.array(z.string())
)
const processStringArraySchema = z.preprocess(
(val) => (typeof val === 'string' ? [val] : val),
z.array(z.string())
)
Thanks in advance!
1 Reply
extended-salmon
extended-salmon5mo ago
can you please post a complete minimal example by forking one of the existing stackblitz examples? e.g. https://tanstack.com/router/latest/docs/framework/react/examples/quickstart-file-based
React TanStack Router Quickstart File Based Example | TanStack Rout...
An example showing how to implement Quickstart File Based in React using TanStack Router.

Did you find this page helpful?