Suppose we have a discriminated union
export const duParser = z.discriminatedUnion('type', [
z.object({
type: z.literal('a'),
id: aParser,
}),
z.object({
type: z.literal('b'),
id: bParser,
}),
]);
The inferred result using z.infer would look like
{type: 'a', id: A} | {type: 'b', id: B}
Now, the goal is to obtain a parser and create a specific type from it, for example:
Rename the union field (type) to another name (e.g. type -> type2):
{type2: 'a', id: A} | {type2: 'b', id: B}
Map other fields (although I acknowledge this can be more complex):
{type: 'a', id2: A} | {type: 'b', id2: B}
The scenario involves having a generic parser that outputs {type: ..., id: ...}
, which needs to be combined with a flat structure parser, resulting in prefixed fields for the discriminated union. The requirement for the flat parser stems from the fact that the parsed data represents an HTTP query string:
rootField1=value1&rootField2=value2&subfieldId=subValue1&subfieldType=a
where subfieldId
and subfieldType
correspond to the "id" and "type" attributes of the original discriminatedUnion. However, retaining them as "id" and "type" is not ideal as these attributes are part of a different abstraction level (the root entity may have its own id and type).
Typically, a nested structure would be utilized in this case, but there's curiosity about whether Zod allows for flattening and mapping field names simultaneously.