TanStackT
TanStack9mo ago
1 reply
moderate-tomato

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())


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"
  }
]

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())
)


Thanks in advance!
Was this page helpful?