Mugetsu
Mugetsu2y ago

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)}`
...
}),
})
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 ...
4 Replies
Nick
Nick2y ago
Same way as normal in typescript
Nick
Nick2y ago
Documentation - Narrowing
Understand how TypeScript uses JavaScript knowledge to reduce the amount of type syntax in your projects.
Nick
Nick2y ago
Type also needs to be a z.literal, not sure what you're doing there
Mugetsu
Mugetsu2y ago
Thx got it.