Steve - I have this unique case where I want to...
I have this unique case where I want to filter out elements that do not match my union. Is there any way to do that using zod?
Basically:
z.union([ ... ]).strip()
Solution:Jump to solution
```ts
export const TipTapDocumentDto = z
.object({
type: z.literal("doc"),
attrs: z.object({...
13 Replies
Currently I am thinking of using
z.preprocess
, would this be the way to go?What do you mean "filter out"? Are you working with an array of this union?
Oh yeah, sorry, correct.
In the content property, I have an array of a union of objects, also having a
type
property. And for now I just don't want to bother with anything that does not have type
being equal to 'heading'
or 'paragraph'
for context:I would probably use
catch
and transform
with a filterI would probably use catch and transform with a filterTransform would be executed on the output, right? I want to filter it out of the input for now
.catch
would be possible for now.Lemme demonstrate, maybe we're saying the same thing
Solution
Would it modify my output type to also include null or not?
I am afraid it would, let me test
This works brilliantly, thanks @Scott Trinh !
yeah, the transform will correctly remove the
null
type due to the type guard filter
.You're a genius
🙇♂️
If you ever need to hand
null
as a valid member, the same thing works if you use a custom sentinel value instead of null
.sweet