diceline-chartmagnifiermouse-upquestion-marktwitter-whiteTwitter_Logo_Blue

Today I Learned

How to dynamically infer TypeScript single object types from tRPC query outputs

This is how you can dynamically infer a single object type from a tRPC Query returning an array of elements of that specific type:

export const exampleRouter = router({
  exampleQuery: exampleQueryImplementation,
});

// extracting a single object type from an array of that type 
export type ArrayElement<ArrayType extends unknown[] | null> =
  ArrayType extends (infer ElementType)[] ? ElementType : never;

// the output types of a specific router, indexable by query identifiers
type RouterOutput = inferRouterOutputs<typeof exampleRouter>;

// return type of a single query
export type QueryOutputArray = RouterOutput['exampleQuery'];

// the type of each element from the returned array
export type QueryOutputObject = ArrayElement<QueryOutputArray>;