[Typescript] How to infer Route API return type?
Unanswered
Common Greenshank posted this in #help-forum
Common GreenshankOP
Greeting, I would like to dynamically infer the return type of the Route API:
I tried to use the
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 ? 
4 Replies
@Common Greenshank Greeting, I would like to dynamically infer the return type of the Route API:
typescript
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:753870957348913232>
You are supposed to
1) First check the response status is ok using res.ok
2) then do
3) then parse the json you got from step 2.
If you have a validation library like Zod, this will be quite easy. Maybe just using a typescript
1) First check the response status is ok using res.ok
2) then do
await res.json() 3) then parse the json you got from step 2.
If you have a validation library like Zod, this will be quite easy. Maybe just using a typescript
type and then casting the response json to that type might work otherwise.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;