4

Supposed I am writing a Node.js hello world server. Then as the callback to the http.createServer function I have a function that basically looks like this:

(req, res) => {
  // ...
}

Now, if I want to do this in TypeScript I would like to tell the compiler that req and res are the appropriate objects from Node.js. How do I add these as types? Basically this has to look like this:

(req: X, res: Y): void => {
  // ...
}

But what do I have to provide for X and Y? I don't want to recreate everything from scratch, and I suppose there has to be some mechanism to refer to an existing type, hasn't it?

I suppose that the types for req and res have already been defined somewhere, e.g. in @types/node. How do I use one of those types defined there in my own code?

Golo Roden
  • 140,679
  • 96
  • 298
  • 425
  • You wan't to use same typing at lots of places ? if yes this is [`possible duplicate`](https://stackoverflow.com/questions/42984889/global-types-in-typescript) – Code Maniac Jul 21 '19 at 09:54
  • I think you might be looking for the `typeof` Typescript operator – CertainPerformance Jul 21 '19 at 09:54
  • I suppose that the types for `req` and `res` have already been defined, e.g. in `@types/node`. How do I use one of those types defined there in my own code? – Golo Roden Jul 21 '19 at 09:55

1 Answers1

4

In http.d.ts, RequestListener type is declared.

type RequestListener = (req: IncomingMessage, res: ServerResponse) => void;

You can import those types from http module.

import { IncomingMessage, ServerResponse } from 'http';

const requestListener = (req: IncomingMessage, res: ServerResponse): void => {
}
zmag
  • 7,825
  • 12
  • 32
  • 42