Unreported variable type error in class constructor

Asked

Viewed 57 times

0

I’m creating a class of ErrorHandler for an API. When creating variables in the class constructor, Typescript accuses that variable statusCode does not have a defined type:

interface ErrorObj {
  statusCode: number;
  message: string;
}

class ErrorHandler extends Error {
  constructor({ statusCode, message }: ErrorObj) {
    super();
    this.statusCode = statusCode; // variável que o TypeScript acusa erro de tipo
    this.message = message;
  }
}

I get this mistake:

Property 'statusCode' does not exist on type 'ErrorHandler'. ts(2339)

This typing would not come from the interface?

  • Hello Matheus, although the answer of Luiz explain well where the fault was, I closed the question because it is a simple error of use/ typing (I do not speak of parser error) that really is very occasional to occur and if translate the "error message" would help to understand the problem easily. More details: https://answall.com/help/on-topic - Thank you for understanding, and welcome to the website.

1 answer

3


Notice that the class ErrorHandler extend Error (and therefore must follow the contract stipulated by Error).

However, it does not define any property statusCode explicitly, so that the type to statusCode nay exists in the definition of the class ErrorHandler.

That’s why we define message no error. The property message already is defined in the class Error, so that their statement, although present, is implied.

Therefore, you must declare the property and its type in the class:

interface ErrorObj {
  statusCode: number;
  message: string;
}

class ErrorHandler extends Error {
  // Declarando a propriedade `statusCode`:
  statusCode: number;

  constructor({ statusCode, message }: ErrorObj) {
    super();
    this.statusCode = statusCode;
    this.message = message;
  }
}

It is important to keep in mind that the class type is different from the type of one of the constructor parameters. Note that the interface ErrorObj is defining the type of first constructor parameter, but not the class itself.

Because of this, the interface type in no way reflects on the class type signature.

  • 2

    Who gave negative could explain the reason, please?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.