Borislav Hadzhiev
Thu Mar 10 2022·2 min read
Photo by Lukas Eggers
The error "Constructors for derived classes must contain a super call" occurs
when a parent class is extended without calling the super()
method in the
constructor of the child. To solve the error, call the super()
method in the
constructor of the child class.
Here is an example of how the error occurs.
class Parent { name = 'Parent'; constructor(public a: number, public b: number) { this.a = a; this.b = b; } } class Child extends Parent { name = 'Child'; // ⛔️ Error: Constructors for derived // classes must contain a 'super' call.ts(2377) constructor(public a: number) { this.a = a; } }
We can't access the this
keyword in the constructor of the child class without
calling the super()
method first.
To solve the error, call super() in the child classes' constructor.
class Parent { name = 'Parent'; constructor(public a: number, public b: number) { this.a = a; this.b = b; } } class Child extends Parent { name = 'Child'; constructor(public a: number) { super(a, a); // 👈️ call super() here this.a = a; } }
The super()
method should be called before accessing the this
keyword in the
child's constructor.
super()
call depends on what parameters the parent classes' constructor takes.In the example above, the constructor of the parent class takes 2 parameters of
type number
.
You have to provide all of the parameters the parent class requires, because
when you call the super()
method, you're actually calling the constructor of
the parent class.
super()
method, you are able to use the this
keyword in the constructor of the child class.You can imagine that the super
keyword is a reference to the parent class.
You might also see the super
keyword being used when a child has to refer to a
method of a parent class.
class Parent { name = 'Parent'; constructor(public a: number, public b: number) { this.a = a; this.b = b; } doMath(): number { return this.a + this.b; } } class Child extends Parent { name = 'Child'; constructor(public a: number) { super(a, a); this.a = a; } doMath(): number { // 👇️ super.doMath() calls doMath method of parent return this.a * this.a + super.doMath(); } } const child1 = new Child(3); // 👇️ (3 * 3) + (3 + 3) = 15 console.log(child1.doMath()); // 👉️ 15
doMath
method and uses the super
keyword to invoke the doMath
method of the parent class.These are the 2 most common uses of the super
keyword in classes:
this
keyword