Search code examples
typescriptconstructorsuper

Why does TypeScript require the deriving class to call super(), even though the parent class has no constructor?


I'm new-ish to class-based programming, I'm working on an API made in TypeScript.

Let's say I've got this code:

import { Router } from "express";

export default class BaseController {
  public router = Router();
}

and I extend another class from that:

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!");
  }
}

When I remove super(); my code will not compile because of the following error message: Constructors for derived classes must contain a 'super' call.

I know that super is used to call the constructor for the parent class, but my parent class does not need nor does not have a constructor. This basically means that i'm calling an empty function.

Question: Why do I need to call super(); on a derived class, when the parent class has no constructor? (So you basically don't call anything if I'm correct)


Solution

  • you can check how it will be transpiled to javascript in typescript playground

    from your example property initializer will be moved into constructor therefore call to super is demanded

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