how to change the properties of a express function?

You could extend the original res param to create the one you need:

type ArgumentsType<T extends (...args: any[]) => any> = T extends (
  ...args: infer A
) => any
  ? A
  : never;

type Args = ArgumentsType<typeof app.get>; // get the arguments of app.get
type subApplication = Args[1]; // select the second param, the function
type application = ArgumentsType<subApplication>; // get the argument of the funcion
type res = application[1]; // select the second param: res

// Extend res and overwrite the original send method
interface myCustomRes extends res {
  send: (arg: object) => any; // force send to only admit object
}

app.get("/", function (req, res: myCustomRes) {
  res.send("Hello World!"); // Error because we are using string
  res.send({ message: "Hello World!" }); // Ok because we are using object!
});

Check the demo

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top