14

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;
  }
}

3 Answers 3

37

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;
}
Sign up to request clarification or add additional context in comments.

Comments

9

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.

Comments

1

This is because not every Error object needs to have a syscall property.

You may be able to fix it changing this:

function onError(error: Error) {
  // [ts] property syscall does not exist on error
  if (error.syscall !== 'listen') {
    throw error;
  }
}

to this:

function onError(error: any) {
  if (error.syscall !== 'listen') {
    throw error;
  }
}

See this issue comments for some background:

2 Comments

Yes. This is exactly what I want to say. I though @types/node has already got build-in type for this callback. But I still want to use static checking instead of using any
Absolute wrong thing to do, you're just dropping the use of types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.