You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When a procedure accepts a union as input, it would be nice to be able to narrow the output type based on the input.
constzCookie=z.object({chocolateChips: z.number().min(50)});constzBrownie=z.object({almondChips: z.number().max(10)});constzBiscuit=z.union([zCookie,zBrownie]);typeCookie=z.infer<typeofzCookie>;typeBrownie=z.infer<typeofzBrownie>;constappRouter=router({gimmeBiscuit: authenticatedProcedure.input(z.enum(['cookie','brownie'])).output(zBiscuit).mutation(async({ input })=>{/* bake some biscuits */})});
A caller asking for a cookie will receive an object of type Cookie | Brownie. While it is possible to pick the right output validator based on the input by passing a function to output, the output type will not be tied to the input type.
I tried to think about something that is feasible with TypeScript and came up with this API :
constappRouter=router({gimmeBiscuit: authenticatedProcedure.inputOutput(z.literal('cookie'),zCookie).inputOutput(z.literal('brownie'),zBrownie).mutation(async({ input })=>{/* bake some biscuits */})});
Another option would be to update the signature of the output method to allow a function parameter that bind the input type to the return type of the function through a generic, but I'm not sure of the implications of such update.
duplicateThis issue or pull request already exists
2 participants
Heading
Bold
Italic
Quote
Code
Link
Numbered list
Unordered list
Task list
Attach files
Mention
Reference
Menu
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
When a procedure accepts a union as input, it would be nice to be able to narrow the output type based on the input.
A caller asking for a
cookie
will receive an object of typeCookie | Brownie
. While it is possible to pick the right output validator based on the input by passing a function tooutput
, the output type will not be tied to the input type.I tried to think about something that is feasible with TypeScript and came up with this API :
Another option would be to update the signature of the
output
method to allow a function parameter that bind the input type to the return type of the function through a generic, but I'm not sure of the implications of such update.Beta Was this translation helpful? Give feedback.
All reactions