MugetsuM
tRPC3y ago
4 replies
Mugetsu

Discriminated union handle

How Do I handle Input type if its discriminated union??

export const batchTasksRouter = createTRPCRouter({
  requestExport: procedure
    .input(
      z.discriminatedUnion('type', [
        z.object({
          type: ExportsZSchema,
        }),
        z.object({
          type: ExportsZSchema,
          id: z.string().uuid(),
        }),
        z.object({
          type: ExportsZSchema,
          id: z.string().uuid(),
          query: z.object({
            from: z.string(),
            to: z.string(),
            type: z.string().optional(),
          }),
        }),
      ]),
    )
    .query(async ({ ctx, input }) => {
      const { id, query, type } = input // <------- TYPESCRIPT ERRRORS that id and query not exists
      let urlSuffix = type

      if (id) urlSuffix += `/${id}`

      if (query) urlSuffix += `?${querystring.stringify(query)}`
...
    }),
})

TS2339: Property 'id' does not exist on type ...
TS2339: Property 'query' does not exist on type ...
Was this page helpful?