I'm in the process of converting my Express app to TypeScript and running into an issue with middleware storing data in the request object.
Even though I define req.payload
, I keep encountering an error. Here's a snippet 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}`);
});
Attempting to manipulate req.payload
triggers this TypeScript error:
Property 'payload' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.(2339)
To resolve this, I referred to this article on extending Express Request interface.
I added a file @types/express/index.d.ts
like so:
// @types/express/index.d.ts
declare global {
namespace Express {
interface Request {
payload?: {};
}
}
}
I updated tsconfig.json
as follows:
// tsconfig.json
// ...
"typeRoots": [
"@types",
"./node_modules/@types"
]
Despite trying various configurations in the declaration file and tsconfig.json, I'm still stuck with the same error.
Is there anything else I should be doing?