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?
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 => {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With