0
votes

I'm trying to use intersection types to extend a function that has already an incomplete definition.

With this code :

WebApp.connectHandlers.use("/route", (req:IncomingMessage, res:ServerResponse)=>{
   //do stuff with req and res
})

I'm using a connect middleware body-parser which is adding a body field to the req Object so it's not anymore just an IncomingMessage but an IncomingMessage with a body field.

I have tried to define an intersection type like this

interface bodyContent = {
   body : {
      foo : string
      }

type intersectionType = bodyContent & IncomingMessage;

and rewriting my binding like this :

WebApp.connectHandlers.use("/route", (req:intersectionType, res:ServerResponse)=>{
   //do stuff with req.body and res
})

But Typescript is still complaining that the callback provided has the wrong format since use is not defined like this. How do i extend the existing official definition of this software without modifying it.

Thank you.

Edit: Since it has been asked, here is use type definition :

use(route: string, fn: HandleFunction)

HandleFunction definition :

type handleFunction = (req: IncomingMessage, res: http.ServerResponse) => void;
1
How is use defined - what is its type signature?kaya3

1 Answers

1
votes

You could use any type like so

WebApp.connectHandlers.use("/route", (req: any, res: ServerResponse)=>{ //do stuff with req and res })

and typescript wouldn't complain anymore, but you probably don't want that, because using any is terrible.

Here's a better solution:

WebApp.connectHandlers.use("/route", (req: IncomingMessage, res: ServerResponse)=>{ const reqWithBody = req as intersectionType; //do stuff with reqWithBody and res })

This also feels like a hack, but I don't see a better way out of this situation, since you don't want to change the library's source code and you're dependent on them, and they haven't taken this situation into account.