T
tRPC

Discriminated union handle

Discriminated union handle

MMugetsu3/10/2023
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)}`
...
}),
})
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 ...
Nnlucas3/10/2023
Same way as normal in typescript https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions Type also needs to be a z.literal, not sure what you're doing there
MMugetsu3/10/2023
Thx got it.

Looking for more? Join the community!

T
tRPC

Discriminated union handle

Join Server