How to do declaration merging for `express.Response` correctly with type inference

Viewed 205

I'm trying to alter the declaration of Response.locals to achieve an extra bit of type safety. Following the answer to a similar question I added the following index.d.ts to my project:

import * as express from "express";

interface Locals {
  someData: string
}

declare module "express" {
  export interface Response {
    locals: Locals;
  }
}

This works quite well when used as follows:

app.post("/somePath", (req, res: express.Response) => {
  // res.locals has type `Locals` here
});

But if I omit to explicitly state the type of res, the compiler seems to infer a different type for Response, where Response.locals is of type any again

app.post("/somePath", (req, res) => {
  // oops, res.locals has type `any` here
});

leaving all the room for typos (say somedata instead of someData) I initially wanted to avoid by using Typescript.

What's wrong with my augmentaion of the Response interface?

0 Answers
Related