解决 TypeScript中 Constructors for derived classes must contain a super call 错误

当扩展父类而不调用子类的构造函数中的 super() 方法时,会出现错误“Constructors for derived classes must contain a super call”。 要解决该错误,需要在子类的构造函数中调用 super() 方法。

下面我们看一个会产生该错误的示例

classParent {

name = 'Parent';

constructor(public a: number, public b: number) {

this.a = a;

this.b = b;

}

}

classChildextendsParent {

name = 'Child';

// Error: Constructors for derived

// classes must contain a 'super' call.ts(2377)

constructor(public a: number) {

this.a = a;

}

}

上面代码执行时会产生错误,如下所示:

TypeScript Constructors for derived classes must contain a super call 错误

如果不先调用 super() 方法,我们就无法访问子类的构造函数中的 this 关键字。

要解决该错误,需要在子类的构造函数中调用 super()。

classParent {

name = 'Parent';

constructor(public a: number, public b: number) {

this.a = a;

this.b = b;

}

}

classChildextendsParent {

name = 'Child';

constructor(public a: number) {

super(a, a); // 这里调用 super()

this.a = a;

}

}

super() 方法应该在访问子构造函数中的 this 关键字之前调用。

该方法调用父类的构造函数,因此传递给 super() 调用的参数取决于父类的构造函数采用的参数。

在上面的例子中,父类的构造函数接受了 2 个 number 类型的参数。

我们必须提供父类所需的所有参数,因为当调用 super() 方法时,实际上是在调用父类的构造函数。

一旦调用了 super() 方法,就可以在子类的构造函数中使用 this 关键字。

我们可以想象 super 关键字是对父类的引用。

当子类必须引用父类的方法时,我们可能还会看到使用 super 关键字。

classParent {

name = 'Parent';

constructor(public a: number, public b: number) {

this.a = a;

this.b = b;

}

doMath(): number {

returnthis.a + this.b;

}

}

classChildextendsParent {

name = 'Child';

constructor(public a: number) {

super(a, a);

this.a = a;

}

doMath(): number {

// super.doMath() 调用父类的 doMath 方法

returnthis.a * this.a + super.doMath();

}

}

const child1 = newChild(3);

// (3 * 3) + (3 + 3) = 15

console.log(child1.doMath()); // 15

上例中的子类覆盖 doMath 方法,使用 super 关键字调用父类的doMath方法。

以下是类中 super 关键字的两种最常见用法:

  • 调用父级的构造函数,所以可以使用 this 关键字

  • 覆盖时引用父类的方法

本文转载自:迹忆客(https://www.jiyik.com)

以上是 解决 TypeScript中 Constructors for derived classes must contain a super call 错误 的全部内容, 来源链接: utcz.com/z/290301.html

回到顶部