Is there a way omit keys from a discriminated union? Or an alternative way to achieve something similar? #1434
-
|
We're hoping to do something like this: export const BaseTemplateSchema = z.object({
id: z.string(),
name: z.string(),
lastUpdated: z.string().optional(),
createdOn: z.string(),
})
export const CommunicationTemplateSchema = BaseTemplateSchema.merge(
z.object({
type: z.literal('templates:types:communication'),
smsTemplate: z.string().optional().nullable(),
subject: z.string(),
htmlTemplate: z.string(),
textTemplate: z.string(),
})
)
export const NoteTemplateSchema = BaseTemplateSchema.merge(
z.object({
type: z.literal('templates:types:note'),
textTemplate: z.string(),
})
)
export const TemplateSchema = z.discriminatedUnion('type', [
CommunicationTemplateSchema,
NoteTemplateSchema,
])
export const CreateTemplateSchema = TemplateSchema.omit({
id: true,
createdOn: true,
lastUpdated: true,
})This doesn't work when we get to Essentially what we're trying to do is to have a TemplateSchema type that has different keys depending on the Is there a way to achieve this with zod? Wether using discriminated unions or something else? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 1 reply
-
|
Yeah, we've talked previously about adding the other const createOmits = {
id: true,
createdOn: true,
lastUpdated: true,
} as const;
export const CreateTemplateSchema = z.discriminatedUnion("type", [
CommunicationTemplateSchema.omit(createOmits),
NoteTemplateSchema.omit(createOmits),
]); |
Beta Was this translation helpful? Give feedback.
-
|
Somewhat related: I needed Omit for the type created by |
Beta Was this translation helpful? Give feedback.
-
|
Any update for this? |
Beta Was this translation helpful? Give feedback.
-
const MySchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('example1'), foo: z.string() }),
z.object({ type: z.literal('example2'), bar: z.number() }),
])
const myNewTypeWithoutEx2: Exclude<
z.infer<typeof MySchema>,
{ type: 'example2' }
> |
Beta Was this translation helpful? Give feedback.
Yeah, we've talked previously about adding the other
ZodObjectmethods toZodDiscriminatedUnion, but haven't made any progress on that that I'm aware of. The temporary fix is to make a separate union like this:TypeScript Playground