Currently, I am in the process of developing a node server using Express and TypeScript 1.7. The middleware I am working with is tailored to my project and extends the existing express Request or Response interface. However, I am encountering issues as TypeScript keeps complaining about not finding certain elements in req or res. I have come across some discussions on this topic but haven't found a clear-cut solution yet.
I've examined the definition of an already existing middleware, but integrating it without having to manually create separate d.ts files and reference them in typings/tsd.d.ts has been a challenge. Here is how my setup looks like:
// middleware/foobar.ts
declare module Express {
export interface Request {
foobar?: string;
}
}
/* My custom middleware for the project appends 'foobar' to the request */
export = function(req: Express.Request, res, next) {
req.foobar = 'FooBar';
next();
};
// main.ts
import express = require('express');
var app = express();
app.use(require('./middleware/foobar'));
app.get('/foobar', (req, res) => {
/* TypeScript error: Property 'foobar' does not exist on type 'Request' */
res.send(req.foobar);
});
Any suggestions on the best approach to extend express' Request and Response interfaces? Ideally, I would like to achieve this without the need for separate d.ts files, modifying anything within the typings directory, or utilizing
/// <reference path="..." />
comments.