Search code examples
typescriptexpress

TS2339: Error extending Express Request (e.g. req.payload)


I am currently migrating a Express app to TypeScript.

I have some middleware that needs to store info in the request object (e.g. req.payload) but I keep getting an error.

Here's a simplified version of my code:

// server.ts

import { Application } from 'express';
import { Request, Response, NextFunction } from 'express';

import express from 'express';
const app: Application = express();

function middleware1(req: Request, res: Response, next: NextFunction) {
  req.payload = {
    name: 'bob',
  };

  next();
}

app.use(middleware1);

app.get('/', (req, res, next) => {
  res.json({ message: 'hello world' });
});

const PORT = process.env.PORT || 5005;

app.listen(PORT, () => {
  console.log(`Server listening on port http://localhost:${PORT}`);
});

If I try to store something in req.payload, TypeScript will complain:

Property 'payload' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.(2339)

so I'm trying to extend the Request interface from Express by following this article.

I have created the file @types/express/index.d.ts with the following content:

// @types/express/index.d.ts

declare global {
  namespace Express {
    interface Request {
      payload?: {};
    }
  }
}

And I've updated tsconfig.json to include the following:


// tsconfig.json

// ...

    "typeRoots": [
      "@types",
      "./node_modules/@types"
    ]

I've tried multiple configurations in the declaration file and in tsconfig.json; however, I keep getting the same error.

Is there any other step needed?

Here's a simplified version of the code on StackBlitz


Solution

  • I dont know about the global, and also you need to declare namespace I think. So this should work:

    @types/express/index.d.ts:

    declare namespace Express {
      interface Request {
        payload?: {};
      }
    }
    
    

    For ts-node, you may also need to add the property "files" to tsconfig.json:

    {
      "compilerOptions": {
        //...
      },
      "files": ["src/@types/express/index.d.ts"]
    }
    

    Here's a link to stackblitz: https://stackblitz.com/edit/stackblitz-starters-d48bzi?file=src%2F%40types%2Fexpress%2Findex.d.ts,src%2Fserver.ts