简体   繁体   中英

Property 'status' does not exist on type 'ServerResponse' (TS2339)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM