I'm transforming Typescript for my backend codebase, but when listening to http server Error Event
, I'm facing an issue about [ts] property syscall does not exist on error
. I think the Error type is wrong here, but apparently Node.js does not provide the default error type for this callback function. Anyone can help me with the correct Error type?
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World!');
res.end();
})
server.listen(3000);
server.on('error', onError);
function onError(error: Error) {
// [ts] property syscall does not exist on error
if (error.syscall !== 'listen') {
throw error;
}
}
The http. createServer() method turns your computer into an HTTP server. The http. createServer() method creates an HTTP Server object. The HTTP Server object can listen to ports on your computer and execute a function, a requestListener, each time a request is made.
Node. js has a built-in module called HTTP, which allows Node. js to transfer data over the Hyper Text Transfer Protocol (HTTP). The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client.
Trying changing the type of your error
variable from Error
to NodeJS.ErrnoException
. This type is an interface that extends the base Error
interface and adds the syscall
property, among others.
Source: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/index.d.ts#L401
export interface ErrnoException extends Error {
errno?: number;
code?: string;
path?: string;
syscall?: string;
stack?: string;
}
If you're using types, like @types/node
, the class you want to use is NodeJS.ErrnoException
. Saying use any
to solve the problem of lacking a type, is the same as saying if you want to stop punctures on a car, take off the wheels.
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