Typed API routes from GET method?
Answered
Mini Rex posted this in #help-forum
Mini RexOP
Hey Everyone, has anyone had success with getting the return types for Typescript, from an API route?
Let say I have this data:
When calling the route, how to get typed response from the route fetch?
Tried the following without any luck:
Let say I have this data:
export async function GET(request: Request) {
return Response.json({
data: {
test: 'string',
},
});
}When calling the route, how to get typed response from the route fetch?
Tried the following without any luck:
import { GET } from "@/app/api/route";
import { NextResponse } from "next/server";
type TypedResponse =
ReturnType<typeof GET> extends NextResponse<infer T> ? T : never;Answered by joulev
nope, impossible.
if you want type-safe api routes just use trpc https://trpc.io
Response is a generic class, you can get literally anything from a Response object not necessarily just json, so implementing a TypedResponse is not possible.if you want type-safe api routes just use trpc https://trpc.io
2 Replies
@Mini Rex Hey Everyone, has anyone had success with getting the return types for Typescript, from an API route?
Let say I have this data:
ts
export async function GET(request: Request) {
return Response.json({
data: {
test: 'string',
},
});
}
When calling the route, how to get typed response from the route fetch?
Tried the following without any luck:
ts
import { GET } from "@/app/api/route";
import { NextResponse } from "next/server";
type TypedResponse =
ReturnType<typeof GET> extends NextResponse<infer T> ? T : never;
nope, impossible.
if you want type-safe api routes just use trpc https://trpc.io
Response is a generic class, you can get literally anything from a Response object not necessarily just json, so implementing a TypedResponse is not possible.if you want type-safe api routes just use trpc https://trpc.io
Answer
Mini RexOP
Guess it's just as easy to just infer the response with Zod or Valibot then?