I have tried creating an interface, installing react types, the only way this works is when i put the code in JavaScript but in a TS project, it gives me error:
Property 'status' does not exist on type 'ServerResponse' (TS2339)
Here's the code:
import multer from 'multer';
import nc from "next-connect";
const upload = multer({
storage: multer.diskStorage({
destination: './public/uploads',
filename: (req, file, cb) => cb(null, file.originalname),
}),
});
const apiRoute = nc({
onError(error, req, res) {
res.status(501).json({ error: `Sorry something Happened! ${error.message}` });
},
onNoMatch(req, res) {
res.status(405).json({ error: `Method '${req.method}' Not Allowed` });
},
});
apiRoute.use(upload.array('theFiles'));
apiRoute.post((req, res) => {
res.status(200).json({ data: 'success' });
});
export default apiRoute;
export const config = {
api: {
bodyParser: false, // Disallow body parsing, consume as stream
},
};
How to fix the typings?
By default, the base interfaces of req
and res
are IncomingMessage
and ServerResponse
. When using in API Routes, you should set them to NextApiRequest
and NextApiResponse
by providing the generics to the factory function like so:
import { NextApiRequest, NextApiResponse } from "next";
import nc from "next-connect";
const apiRoute = nc<NextApiRequest, NextApiResponse>({
onError(error, req, res) {
res.status(501).json({ error: `Sorry something Happened! ${error.message}` })
},
onNoMatch(req, res) {
res.status(405).json({ error: `Method '${req.method}' Not Allowed` })
},
})
apiRoute.post((req, res) => {
res.status(200).json({ data: 'success' })
})
It will provide you the correct typings, so that you can use status
method of res
object without any TypeScript error.
See the docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With