typed-route-handler
typed-route-handler copied to clipboard
Type inference instead of`typedFetch`
Hi, @venables, I came across this repo and it looks super interesting!
I definitely plan to give it a try soon :)
Until then - Given your example:
type ResponseData = {
result: string
over: number
}
export const GET = handler<ResponseData>(async (req) => {
return NextResponse.json({
result: "this response is type-checked",
over: 9000
})
})
It seems possible to use type inference to create a type-safe helper safer than typedFetch
Something like this: (according to GPT4)
import { GET } from './your-nextjs-router-file'; // Update the path accordingly
type ResponseData = ReturnType<typeof GET>;
async function fetchData(): Promise<ResponseData> {
const response = await fetch('/your-api-endpoint'); // Update the API endpoint
const responseData: ResponseData = await response.json();
return responseData;
}
fetchData().then(data => {
console.log(data); // This will have the correct type ResponseData
}).catch(error => {
console.error('Error fetching data:', error);
});
Of course you would need to generalize it accept any GET and return the correct type
WDYT?
Erik.