Last updated: Feb 28, 2024
Reading timeยท3 min
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.
super()
method in the child class's constructorTo solve the error, call super() in the child class's constructor.
class Parent { name = 'Parent'; constructor( public a: number, public b: number, ) { this.a = a; this.b = b; } } class Child extends Parent { override name = 'Child'; constructor(public override 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 class's constructor takes.In the example, the constructor of the parent class takes 2 parameters of type
number
.
You have to provide all of the parameters the parent class takes 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 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 { override name = 'Child'; constructor(public override a: number) { super(a, a); this.a = a; } override 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
keywordI've also written an article on how to create a custom class that extends from Error.
You can learn more about the related topics by checking out the following tutorials: