简体   繁体   中英

Typescript This expression is not constructable. error on inherited class structure

I'm new to Typescript and I'm trying to personalize my error classes inside the application.

I have totally four classes; Exception , GenericError , BaseService , CarService two main and two inherited. GenericError extends ExceptionClass and CarService extends BaseService . I'm not be able to change constructor property of GenericError class. I'm getting this error;

This expression is not constructable.

TS Snippet

What is wrong with my class inheritence logic?

// Exception.ts
class ExceptionClass extends Error {
  status: number;
  message: string;
  errors?: object;
  constructor(status: number, message: string, errors?: object) {
    super(message);
    this.status = status;
    this.message = message;
    this.errors = errors;
  }
}
// GenericError.ts
class GenericException extends ExceptionClass {
  constructor(message?: string) {
    super(400, message || 'Internal Error');
  }
}
// BaseService.ts
class BaseService {
  genericError: GenericException;

  constructor(message: string) {
    this.genericError = new GenericException();
  }
}
// CarService.ts
export default class CarService extends BaseService {
  constructor() {
        super('')
        console.log("CarService started!");
    }
  async checkCar() {
    return new Promise(async (resolve: any, reject: any) => {
      //** Imagine some business logic that fails */
      const passwordsNotMatchErr = new this.genericError('Fail Reason bla bla');
      return reject(passwordsNotMatchErr);
    })
  }
}

The problem is that in the following line:

const passwordsNotMatchErr = new this.genericError('Fail Reason bla bla');

You are trying to create an instance of a variable that has been instantiated in the constructor of your class. You are trying to do something like const myString = new "I am a string and I can not be instantiated"

When you do:

genericError: GenericException;

What you are doing is defining a class variable which is of GenericExpection type (Remember that only classes can be instantiated, not variables). If you'd like to follow your architecture you can do something like:

  async checkCar() {
    return new Promise(async (resolve: any, reject: any) => {
      //** Imagine some business logic that fails */
      this.genericError = new GenericException('Fail Reason bla bla');
      return reject(this.genericError);
    })
  }

or

  async checkCar() {
    return new Promise(async (resolve: any, reject: any) => {
      //** Imagine some business logic that fails */
      const passwordsNotMatchErr = new GenericException('Fail Reason bla bla');
      return reject(passwordsNotMatchErr);
    })
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM