Skip to content

A way to exclude invalid items? #672

Answered by scotttrinh
kladnik asked this question in Q&A
Discussion options

You must be logged in to vote

I'm not aware of a way to adjust a Zod parser's behavior to get it to simply ignore items rather than throwing an error. You could write an array helper function and use preprocess maybe, but it's not going to be pretty since preprocess starts at unknown and requires you to do your own type narrowing.

If I was trying to implement a solution here, I would specify all of the types, or use z.array(z.any()) and use transform like this:

const array = ['test', 'test2', 'test3', null]
const validatedArray = z.array(z.any())
  .transform(
    (as) => as.filter((a) => z.string().safeParse(a).success)
  )
  .parse(array) // ['test', 'test2', 'test3']

Maybe this is a useful generalization?
CodeSandbox

Replies: 5 comments 3 replies

Comment options

You must be logged in to vote
2 replies
@kladnik
Comment options

@scotttrinh
Comment options

Answer selected by kladnik
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@SharmaTushar
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
7 participants