Search code examples
node.jstypescripthttpserverdefinitelytyped

request.url undefined type, why?


Why request.url is defined as optional within nodejs types? If a Request come to the http server should have the url by definition.

Why there is a question mark here? url?: string;

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/http.d.ts#L288


Solution

  • 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