Next.js Discord

Discord Forum

[Typescript] How to infer Route API return type?

Unanswered
Common Greenshank posted this in #help-forum
Open in Discord
Common GreenshankOP
Greeting, I would like to dynamically infer the return type of the Route API:

async function postHandler(request: NextRequest) {
  // some logic

  return NextResponse.json(
    {
      status: "OK",
      data: {}, // some data
    },
    { status: 200 },
  );
}
export const POST = postHandler;

// not working
export type PostResponse = Awaited<ReturnType<typeof postHandler>>;


I tried to use the ReturnType but I get the NextResponse which is not I wanted. Any idea how to unwrap the NextResponse ? :thank_you:

4 Replies

Common GreenshankOP
I'm using react-query & axios to do the fetching, and both of them cant get the response type returned by the GET handler from nextJS route, hence I need to get the type out from the returned result. I dont want to "hardcode" the return type and cast them as the response type might get updated in the future, and I would like to use the infer method to get the type out.
I would like to use the infered type and use it on the axios method like below:

export const fetchSomeData = (args: Args) =>
  api.post<PostResponse>(`/api/data?args=${args}`);
Common GreenshankOP
In case anyone come across this, I'm able to get the type out by using the following:
export type PostResponse = Awaited<
  ReturnType<typeof postHandler>
> extends NextResponse<infer R>
  ? R
  : never;