Home > Software engineering >  Constructors for derived classes must contain a 'super' call. ts(2377)
Constructors for derived classes must contain a 'super' call. ts(2377)

Time:05-30

This is not the usual problem with a missing super() call. Instead I have a special construct where I need to call super() differently. Check this code:

class A {
    public constructor() {
        console.log("c-tor A");
    }
}

class B extends A {
    public constructor(s: string);
    public constructor(i: number, s: string);
    public constructor(_i: string | number, s?: string) {
        const x = () => {
            s = "";
            super();
        };

        x();
        console.log("c-tor B");
    }
}

const b = new B("");

It runs fine and prints:

c-tor A c-tor B

However, tsc reports the error mentioned in the title:

enter image description here

and I cannot suppress it by using // @ts-ignore. What other option do I have to silence the compiler?

CodePudding user response:

@ts-ignore does the job, but your problem is that es-lint is also complaining. You will need to add eslint-disable constructor-super

class B extends A {
    public constructor(s: string);
    public constructor(i: number, s: string);
    /* eslint-disable constructor-super */
    /* @ts-ignore */
    public constructor(_i: string | number, public s?: string) {
        const x = () => {
            s = '';
            // @ts-ignore
            super();
        };

        x();
        console.log('c-tor B');
    }
}

Playground

CodePudding user response:

This seems to work:

class B extends A {
    public constructor(s: string);
    public constructor(i: number, s: string);
    // @ts-ignore
    public constructor(_i: string | number, s?: string) {
        const x = () => {
            s = "";
            // @ts-ignore
            super();
        };

        x();
        console.log("c-tor B");
    }
}

You need to ignore the entire constructor and also the call to super inside your function as TS doesn't like this.

  • Related