Getting the type of context
Is it possible to get the type on a context object that is passed into a specific TRPC procedure after it is modified by the middleware?
If so, whats the best way to go about this? Thanks
6 Replies
What do you mean by this? What are you trying to do?
When you are using a middleware, context the mutation or query receives is modified by that context. Type-inference might need your help however. https://trpc.io/docs/server/middlewares#authorization, in this example you don't pass the context object back to the opts.next because then TypeScript won't infer that the user is not undefined. That's why you pass the user object directly instead.
Idk if this answers your question?
I am basically looking to create a type that gives me the shape of the context after it is extended by the middleware.
I am sure it’s possible considering the context is properly typed within mutations and queries. I have just been failing at creating it.
So in the example you linked I want a type that tells me the shape of the context including the user that was added into it by the middleware.
I couldn't find if tRPC exposes that, you could try to infer it like so:
But this could break when tRPC updates, so use at your own risk
You may want to open an issue if you want this type of inference out of the box
Much appreciated. I’ll see if that works just for curiosity sake but you’re probably right, might be safer to just open a ticket.
I just tested my solution, it doesn't work. The first generic is the incoming context, the third generic is the overwritten context, in the builder these get combined for the procedure, but that is an internal type util that I cannot make use of, you'd have to copy the Overwrite generic yourself if you want to combine the two.
You can use:
And just make sure that the overwritten context is the same as the incoming context (for example)
If you don't want to always make sure that they are the same you can copy the Overwrite util.
And change the infer utilities to:
Thank you for diving this deep into this, just looking into what you provided now. So since in some of my middlewares I am adding new properties to the context, I dont need the incoming context to match the outgoing so I wanna go with the second Overwrite option I believe