hoangvvo / next-connect

The TypeScript-ready, minimal router and middleware layer for Next.js, Micro, Vercel, or Node.js http/http2
https://www.npmjs.com/package/next-connect
MIT License
1.63k stars 65 forks source link

Typescript Issue - NextApiResponse already declared error #109

Closed NJITman closed 3 years ago

NJITman commented 3 years ago

I am using the following next.js api code to setup a new api.

import { NextApiRequest, NextApiResponse } from 'next';
import nc from 'next-connect';
import cors from 'cors';

const handler = nc<NextApiRequest, NextApiResponse>();

handler
  .use(cors())
  .get((req: NextApiRequest, res: NextApiResponse) => {
    res.send('GET');
  })
  .post((req: NextApiRequest, res: NextApiResponse) => {
    res.json({ method: 'POST' });
  })
  .put(async (req: NextApiRequest, res: NextApiResponse) => {
    res.end('PUT');
  });

export default handler;

eslint is showing the following error:

Parsing error: Identifier 'NextApiResponse' has already been declared for line 5:

const handler = nc<NextApiRequest, NextApiResponse>();

Although it shows as an error, it does not affect building and running the api - it is just an annoyance right now showing 1 PROBLEM due to this issue. I tried added the no-redeclare rule to my eslintrs.json, but that did not work.

Any insight on how to clear this warning/error would be appreciated.

hoangvvo commented 3 years ago

What is your eslint config?

Also for each handler, you don't need to add NextApiRequest and NextApiResponse.

.get((req, res) => {
    res.send('GET');
  })
NJITman commented 3 years ago

.eslintrc.json

{
  "env": {
    "browser": true,
    "es2021": true,
    "node": true
  },
  "extends": ["eslint:recommended", "plugin:react/recommended"],
  "parser": "babel-eslint",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 12,
    "sourceType": "module"
  },
  "plugins": ["react"],
  "rules": {}
}

Today when I re-opened the project to get the config above, I see that eslint is no longer highlighting the NextApiResponse as being re-declared. Perhaps eslint needed to be reloaded to clear the error, since the error did not make sense anyway, it is not being re-declared in that file. I prefer to type all of my arguments for functions and return values, so it is clear the nature of the data being used.