request.url undefined type, why?

Viewed 1577
1 Answers

I don't know much about http/Request in node, but this seems to be the classic example of bad modeling (which is often found in the @types/node definitions, either due to how the types have been written or to the underlying design of the node.js API itself).

IncomingMessage is being modeled as a product type with optional keys instead of as a proper sum type - to distinguish the case of a client request from a server generated one. Comments about the invariants are then put above the single fields, making them useless in terms of TS / static type checking.

Reading just that definition, a better type def could have been:

interface ClientIncomingMessage extends stream.Readable {
  // ... many other fields ...
  url: string;
}

interface ServerIncomingMessage extends stream.Readable {
  // ... many other fields ...
  // no `url` fields here!
}

type IncomingMessage = ClientIncomingMessage | ServerIncomingMessage

Related