Hi,
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"
]
However, I still get the error.
Am I missing something? Any help is really appreciated 🙏