为什么TypeScript要求派生类调用super(),即使父类没有构造函数?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为什么TypeScript要求派生类调用super(),即使父类没有构造函数?相关的知识,希望对你有一定的参考价值。

我是基于类的编程新手,我正在研究用TypeScript制作的API。

假设我有此代码:

import  Router  from "express";

export default class BaseController 
  public router = Router();

并且我从那开始扩展另一个类:

import BaseController from "./BaseController";

export default FooController extends BaseController 
  constuctor() 
    // I will elaborate on this super later in the question
    super();
    this.router.get("/", this.faz);
  

  private faz(req: Request, res: Response) 
    res.status(200).send("boo!");
  

当我删除super();时,由于以下错误消息,我的代码将无法编译:Constructors for derived classes must contain a 'super' call.

我知道super用于调用父类的构造函数,但是我的父类既不需要也没有构造函数。这基本上意味着我正在调用一个空函数。

问题:当父类没有构造函数时,为什么需要在派生类上调用super();(因此,如果我是正确的话,您基本上不会打任何电话)

答案

您可以检查如何将其转换为typescript playground中的javascript

从您的示例属性初始值设定项将移入构造函数,因此需要调用super

export default class BaseController 
    constructor() 
        this.router = Router();
    

以上是关于为什么TypeScript要求派生类调用super(),即使父类没有构造函数?的主要内容,如果未能解决你的问题,请参考以下文章

Typescript派生类和抽象类

12.面向对象(继承/super/接口/抽象类)

从派生类调用重载函数

Typescript错误:当一个类包含初始化属性时,'super'调用必须是构造函数中的第一个语句

解读typescript中 super关键字的用法

python 怎样调用基类函数