5

I tried to migrate my express server code from js to typescript and ran into issues when trying to access fields I added to the request object in my own middleware functions.

For example, I am doing something like this:

app.use((req, res, next) => {
    let account = checkAuthentication(req);
    if(account) {
        req.authenticated = true;
        req.account = account;
        next();
    }
});

Now I want to access those properties later on in my other middleware functions, but the .d.ts file from @types/express defines the req object the same way for all middleware functions of course.

Now I came up with two ways to deal with this, but both seem bad:

  1. Use a typeguard in every middleware function. But then I add useless code to the js output because my routes are setup in a way so that I know at "compile" time what shape my req object has in each middleware function.
  2. Use a type assertion in every middleware function. But then I don't get the benefits of typescript, despite writing my code so that all types are know at compile time, because I basically disable typechecking for the req object then.

So my question is: How, if at all, can I utilize typechecking in that scenario? If I can't, does that mean a framework like express is impossible in a statically typed language (like C#)?

Leander Behr
  • 153
  • 1
  • 2
  • 10

1 Answers1

3

You can use module augmentation to extend the Request type defined in the express module

declare global {
    namespace Express {
         export interface Request {
              account: Account;
              authenticaticated: boolean 
         }
    }
}
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • 6
    But then I change the type of the req object in all my middleware functions right? The idea is to have the type reflect the changing shape of the req object between middleware functions. It's a bit perfectionist but I was wondering if that is possible. – Leander Behr Jan 06 '19 at 19:03
  • 1
    @LeanderBehr this would be great but seems too much dynamic! You can potentially have a different req type for every request! – Elia Dec 23 '20 at 15:21