Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I refer to an existing type from another module in TypeScript?

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?

like image 573
Golo Roden Avatar asked Oct 19 '25 12:10

Golo Roden


1 Answers

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 => {
}
like image 171
zmag Avatar answered Oct 22 '25 02:10

zmag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!