Can not return custom object in ES6 class's constructor in Typescript

Viewed 168

How can we return custom object in Typescript's class constructor if that class has some required attribute. Below is example snippet for my situation in Typescript.

class MyError extends Error {
    customRequiredAttribute: string[];

    constructor(error: any) {
        if (error instanceof MyError) {
            return error;
        } else {
            // do something else to initialize this instance
            super(error);
            this.customRequiredAttribute = [error.message];
        }
    }
}

Please see in the playground.

Above Typescript snippet will produce the following error:

Property 'customRequiredAttribute' has no initializer and is not definitely assigned in the constructor.

While in Javascript, we can achieve that:

class MyError extends Error {
    constructor(error) {
        if (error instanceof MyError) {
            return error;
        } else {
            // do something else to initialize this instance
            super(error);
            this.customRequiredAttribute = [error.message];
        }
    }
}

const MyErrorFromNativeError = new MyError(new Error('has some error'));
const MyErrorFromMyError = new MyError(MyErrorFromNativeError);

console.log("Is both MyError above the same:", MyErrorFromMyError === MyErrorFromNativeError);

1 Answers

This has to do with Strict Class Checking of the TS system. It requires the script to initialize all properties in the constructor. (The global setting is in strictPropertyInitialization flag of the tsconfig)

The best way to get around this error is by initializing the properties.

customRequiredAttribute: string[] = '';

However, this is not applicable in the current scenario as super() statement is not the first item in your constructor.

So, the work around is to disable Strict Class Checking for this property by using the ! syntax.

customRequiredAttribute!: string[];

Related