Home > Net >  Express middleware with TS: void' is not assignable to parameter of type 'PathParams'
Express middleware with TS: void' is not assignable to parameter of type 'PathParams'

Time:08-30

I'm new to typescript and converting my existing JS application. I'm stuck on what seems simple and I've tried searching existing posts to no avail.

I have a simple middleware in Express to log all requests:

const { logger } = require("winston"); 
import express, { Application, Request, Response, NextFunction } from 'express'
...
const app: Application = express();
...
// Middleware - Log all http requests
app.use((req: Request, res: Response, next: NextFunction) => {
  logger.info(`${req.loggedInUser} user [${req.originalUrl}]`) ;
  return next();
});

In typescript this errors with

The last overload gave the following error.
    Argument of type '(req: Request, res: Response, next: NextFunction) => void' is not assignable to parameter of type 'PathParams'.

If it matters I've extended the Request object in index.d.ts:

declare module "express" { 
  export interface Request {
    user: any;
    loggedInUser: any;
    oidc: any;
  }
}

The logger is winston.

Things I've tried:

  • setting the output type of the function to void - didn't work.
  • adding "as express.RequestHandler" after logger similar to Express errors with typescript but no luck.
  • changing Request to type "any" - works but that of course is a poor workaround.
  • Adding path argument "/" - doesn't work thought the IDE (VSCode) no longer reports as an error. Compile fails though.

How can I fix this and what is the concept behind this? Most express docs show using "app.use" without the path for things like helmet, cors etc so it seems like this should be common.

Thank you for your insights!

CodePudding user response:

Try extending the Request object like this instead

declare global {
    namespace Express {
        interface Request {
            user: any;
            loggedInUser: any;
            oidc: any;
        }
    }
}

as mentioned by basarat here: Extend Express Request object using Typescript.

I replicated your error message with my express app using your Request object extension and changing it to the above code fixed the issue.

  • Related