Typed wrappers for procedures
I have a TRPC client with working queries and mutations. I wanted to create wrapper functions for all the procedure so that instead of
trpc.someQuery.query(...)
I can use someQuery(...)
, and instead of trpc.someMutation.mutate(...)
, someMutation(...)
. I'm having trouble with getting the wrapped functions to have correct parameter and return types. Currently I have:
It works in run time, and even shows correct types in VSCode, but when I generate a .d.ts, it says these functions have type (input?: unknown, options?: ProcedureOptions | undefined) => Promise<unknown>
. How can I fix this issue, and is there a more elegant way to create such wrapper functions? I would prefer to use something like export const someQuery = wrap('someQuery')
.9 Replies
i wonder if this is what happens when you try to leverage types that are internal to the package, i have tried myself though tbh
@julius does that sound right? just guessing
Maybe you can get some inspiration from the withQuery() I did for cal.com https://github.com/calcom/cal.com/blob/446c29dd9c576103d7b3caa02317a65b43db0e9d/apps/web/lib/QueryCell.tsx#L86
GitHub
cal.com/QueryCell.tsx at 446c29dd9c576103d7b3caa02317a65b43db0e9d ·...
Scheduling infrastructure for absolutely everyone. - cal.com/QueryCell.tsx at 446c29dd9c576103d7b3caa02317a65b43db0e9d · calcom/cal.com
Would
AnyQueryProcedure
include the type of trpc.someQuery
?I don't understand
DecorateQuery
used in that function. Seems to be this gigantic type defined here https://github.com/trpc/trpc/blob/19c7c27d8ed548b2bc7ab5eb921fd179143aa230/packages/react-query/src/createTRPCReact.tsx#L87GitHub
trpc/createTRPCReact.tsx at 19c7c27d8ed548b2bc7ab5eb921fd179143aa23...
🧙♀️ Move Fast and Break Nothing. End-to-end typesafe APIs made easy. - trpc/createTRPCReact.tsx at 19c7c27d8ed548b2bc7ab5eb921fd179143aa230 · trpc/trpc
DecorateProcedure is the type of like
trpc.post.byId
yes you're extending AnyProcedure - it will get narrowed on invocationWhen I try to assign
const a: AnyQueryProcedure = client.someQuery
, it says it is missing properties _def
, _type
, and _procedure
I'm justing createTRPCProxyClient
, not the with reactso there's a similar type for the vanilla client - so that shouldn't be a problem
why are you giving it the type implicitely?
also - can you tell a bit more about the usecase? why do you want to do this?
I have a mini library that used to have only functions that make fetch calls, and now I'm adding an TRPC API. I want to keep the exports consistent so prefer to export functions for the individual procedures instead of a TRPC client. Also I want the client to be lazily created when any of the procedures is used.
Isn't this basically it?
Not exactly sure what's to be gained by using tRPC types in the implementation here, it would be useful to see a more complete example so we can advise