colinhacks/zod

Discriminated union, cover case where discriminator is missing

Opened this issue · 1 comments

Hey, basically I am validating some json. I have the following setup:

return z.union([
      z.discriminatedUnion('$type', [
        colorToken,
        cubicBezierToken,
        dimensionToken,
        shadowToken,
        borderToken,
        fontFamilyToken,
        fontWeightToken,
        typographyToken,
        viewportRangeToken,
        numberToken,
        durationToken,
        stringToken,
      ]),
      designToken,
    ])

This works really, well, however I would love to add a referenceToken which does NOT have a $type property. This is the only one without the $type property so this is how it could be differentiated. But I don't know how I can implement this in zod. Any ideas? Is this even possible?

Can you give me some examples so I can test this properly?
And as well can you give me the schema on which to test this?
In any case, I believe you can achieve this with .default() as it can give some default value to the key if the key does not exist in the schema.