import { createTRPCClient, httpBatchLink } from '@trpc/client';import type { AppRouter } from '../path/to/server/trpc';const client = createTRPCClient<AppRouter>({ links: [ httpBatchLink({ url: 'http://localhost:3000/trpc', // You can pass any HTTP headers you wish here async headers() { return { authorization: getAuthCookie(), }; }, }), ],});
httpBatchLink is used in configuring tRPC. I was curious about its types, so I started looking at its source code. There is a filed named httpBatchLink.ts found in packages/client/src/links/httpBatchLinks.ts and has about 137 lines of code at the time of writing this article.
export function httpBatchLink<TRouter extends AnyRouter>( opts: HTTPBatchLinkOptions<TRouter['_def']['_config']['$types']>,): TRPCLink<TRouter> {
opts are of type HTTPBatchLinkOptions<TRouter[‘_def’][‘_config’][‘$types’]>,. Let’s follow along the unknowns. I would look at the type definitions for:
- HTTPBatchLinkOptions
- TRouter
export type HTTPBatchLinkOptions<TRoot extends AnyClientTypes> = HTTPLinkBaseOptions<TRoot> & { maxURLLength?: number; /** * Headers to be set on outgoing requests or a callback that of said headers * @see http://trpc.io/docs/client/headers */ headers?: | HTTPHeaders | ((opts: { opList: NonEmptyArray<Operation>; }) => HTTPHeaders | Promise<HTTPHeaders>); };
<TRoot extends AnyClientTypes> is a generic type that extends AnyClientTypes, This means that the generic type must at least have the properties and structure of the type it extends.
export type AnyClientTypes = Pick<AnyRootTypes, 'errorShape' | 'transformer'>;
What is Pick here? I searched for Pick in TS docs and found this:
Constructs a type by picking the set of properties Keys (string literal or union of string literals) from Type.
It could be confusing but important rule here is that types are defined in files, making them colocated with the functions that use these types but also export these types so they can be used across the codebase where required.
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.