node.jstypescriptexpresstype-declaration

typescript and express js. change res json `Response` type


in typescript, I am trying to overwrite the express's Response json object to be a specific type of object to always be used

for example, I want to enforce a interface type that would error out if the following format was not followed

  return res.status(200).json({
    data: ["a", {"a": "b"}],
    success: true,
  });

I attempted to use dts-gen --m express -f src/types/express.d.ts to create the declaration file to modify but it ended in failure.

is there a way to overwrite a specific type on an existing library or do I need to create a declaration file specific to my needs?


Solution

  • interface Json {
      success: boolean;
      data: any[];
    }
    
    type Send<T = Response> = (body?: Json) => T;
    
    interface CustomResponse extends Response {
      json: Send<this>;
    }
    

    I was able to create a new interface that extended this. just needed to learn a bit more :) hopefully this can help out someone else!