Search code examples
javascripttypescriptexceptiontry-catchsuper

Surround super() with try-catch in typescript


Is there way to surround super() calling with try-catch in typescript?

Because there is sometimes error thrown during calling that super() (parent constructor).

Basically it happens when I use custom HTML element, when it is not defined (by calling customElements.define()).

What want I do is to catch that error

Uncaught TypeError: Illegal constructor

and log into console info, that I forget define class XYZ...

Is that possible? Because typescript compiler gives me following error, when I use this constructor:

constructor() {
    try {
        super();
    }
    catch(e) {
        console.log("some info about error");
    }
}

Typescript compiler error:

A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers.


Solution

  • Problem was in initialization of some class properties before constructor calling. I had something like this in my class:

    protected myVar: number = 5;
    constructor() {
        try {
            super();
        }
        catch(e) {
            console.log("some info about error");
        }
    }