Argument of type 'NextHandleFunction' is not assignable to parameter of type 'PathParams'. Type 'NextHandleFunction' is missing the following properties from type

Today while doing my application npm packages upgrade I encountered few errors after upgrading my express  to  4.17.2 and ts-node to 10.5.0 versions.

After version upgrade my visual studio code started complaining about this middleware code
const app = express();
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true, parameterLimit: 1000000 }));

Error:

    **Argument of type 'NextHandleFunction' is not assignable to parameter of type 'PathParams'.  Type 'NextHandleFunction' is missing the following properties from type '(string | RegExp)[]': pop, push, concat, join ..**


When I did npm run start  my terminal was blown up with these errors

C:\SrihariBalgam\Projects\NewADO\node_modules\ts-node\src\index.ts:828
    return new TSError(diagnosticText, diagnosticCodes);
          ^
TSError: ⨯ Unable to compile TypeScript:
app/server.ts:26:9 - error TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type 'NextHandleFunction' is not assignable to parameter of type 'PathParams'.
      Type 'NextHandleFunction' is missing the following properties from type '(string | RegExp)[]': pop, push, concat, join, and 28 m

26 app.use(express.json({ limit: '50mb' }));
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  node_modules/@types/express-serve-static-core/index.d.ts:114:5
    114    <
            ~
    115        P = ParamsDictionary,
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ...
    123        ...handlers: Array<RequestHandlerParams<P, ResBody, ReqBody, ReqQuery, Locals>>
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    124    ): T;
        ~~~~~~~~~
    The last overload is declared here.
app/server.ts:27:9 - error TS2769: No overload matches this call.

Solution:

To address this issue, we need to import  RequestHandler type assertion from express which means, the compiler will assume those middleware has all the type as RequestHandler.

Working Code:

import { RequestHandler } from 'express';

app.use(express.json({ limit: '50mb' }) as RequestHandler);
app.use(express.urlencoded({ limit: '50mb', extended: true, parameterLimit: 1000000 }) as RequestHandler);

Comments