What is the reason behind TypeScript mandating the invocation of super() by the inheriting class, even when the parent class does not have

Just starting out with class-based programming, I've been tinkering with a TypeScript API.

Here's the scenario:

import { Router } from "express";

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

and then I create another class that extends the previous one:

import BaseController from "./BaseController";

export default FooController extends BaseController {
  constuctor() {
    // Further explanation on this super call will be provided later in the question
    super();
    this.router.get("/", this.faz);
  }

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

If I omit super();, my code won't compile and throws this error message:

Constructors for derived classes must contain a 'super' call.

I understand that super is used to invoke the parent class constructor, but since my parent class doesn't have a constructor, it feels like I'm essentially calling an empty function.

Question: Why is it necessary to use super(); in a derived class if the parent class lacks a constructor? (So basically, am I not really calling anything?)

Answer №1

If you want to see how it gets converted into JavaScript, you can use the typescript playground tool.

In your code snippet, the property initializer will be placed inside the constructor function, so calling super is necessary.

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

Answer №2

When using TypeScript, it is important to note that super() may not be strictly checked for being callable. This means that you have the option to omit the super() call if you really want to:

export default FooController extends BaseController {
    constructor() {
        if (false) super()
    }
}

However, it is highly recommended not to do this, especially in scenarios where the super() call is essential. For example, if you have a pre-initialized property like public router, which gets initialized implicitly in the constructor of the superclass (as seen in JavaScript code).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The term 'makeStyles' cannot be found in the '@material-ui/core' module after installing Material-ui-pickers

Can anyone help me with using the inlineDatePicker components from Material UI pickers? I found them here: After running the npm -i command, I encountered an error during compilation: Failed to compile. ./node_modules/material-ui-pickers/dist/material-u ...

Developing a function that takes a parameter which can be used with or without an additional argument when invoked

In my React application, I have a method that accepts a parameter for displaying a modal. const displayModal = (p:Result) => { setConfirm(true); if(p) { //check variable for truthy setSelectedRow(p); } ...

Searching for true values in MongoDB using the query syntax can be challenging

I have a question that might be a bit embarrassing, but I need help with rendering a user search based on both location and date. Our profile object is structured like this: availability: { monday: { type: Boolean, default: false }, tuesday: { type ...

How to Verify User Login Status with Firebase Auth in Node.js Cloud Functions

My goal is to create an Express dynamic web page on Node.js. I aim to execute the following logic on the server (Firebase Cloud Functions) at path /: If the client is currently logged in (Firebase Auth), the home page my_home_page.html should be rendered ...

Utilizing TypeScript with Svelte Components

I've been struggling to implement <svelte:component /> with Typescript without success. Here's my current attempt: Presentation.svelte <script lang="ts"> export let slides; </script> {#each slides as slide} & ...

JavaScript function variable encountering syntax error

My current node version is 12.22.6. I'm struggling to understand why this code isn't working correctly. It seems like I must be missing an important basic concept, but I can't quite pinpoint it. const changeVars = (variable) => { c ...

Is there a way to store my Typeorm data source configuration in a separate variable?

I am currently working with NestJS 10 and TypeORM 0.3.17. In my src/config/data-source.ts file, I have the following code snippet... import * as dotenv from 'dotenv'; import * as dotenvExpand from 'dotenv-expand'; import { DataSource } ...

What are some effective ways to utilize the data gathered from a subscribe() method in a different

handleKeyUp(event: any): void { this.technologiesService.retrieveData(event.target.value) .subscribe(data => { this.myResults = data; }); } The result of data is: https://i.sstatic.net/WjiD4.png I want to assign data as a property fo ...

Define an object type in Typescript that includes both specified properties and an unlimited number of unspecified properties

I'm attempting to create a custom data type using the code below, but it's not working: type CustomDataType { [key: string]: CustomDataType; isValid: boolean; errors?: string[]; } My goal is to have a CustomDataType with an isValid propert ...

Typescript is failing to pick up process.env variables and is treating them as undefined, even though they are

I thought that by adding environment variables to environment.d.ts, they would have the correct types. I am using @types/node as a dev-dependency, and I have defined DATABASE_URL in my environment.d.ts like this: declare global { namespace NodeJS { ...

A guide to effortlessly converting Any[] to CustomType for seamless IntelliSense access to Properties within Angular/Typescript

Our Angular service interacts with the backend to retrieve data and display it on the UI. export interface UserDataResponse { id: number; userName: string; } AngularService_Method1() { return this.http.get<UserDataResponse[]>(this.appUrl + "/Ap ...

Issue with rejecting a promise within a callback function in Ionic 3

Within my Ionic 3 app, I developed a function to retrieve a user's location based on their latitude and longitude coordinates. This function also verifies if the user has location settings enabled. If not, it prompts the user to switch on their locati ...

"Enable the Angular Material checkbox with the value set to checked

Check out my TypeScript code below: import {Component} from '@angular/core'; @Component({ selector: 'checkbox-configuration-example', templateUrl: 'checkbox-configuration-example.html', styleUrls: ['checkbox-config ...

Defining onClick event in Typescript and React.Konva

Struggling with resolving the tslint error Type declaration of 'any' loses type-safety., particularly when it comes to determining the correct type for the Event. Currently converting the Lynda tutorial "Building and Deploying a Full-Stack React ...

What is the best way to set up a JSON attribute with properly formatted JSON data?

Within this code snippet, the variable some is assigned a JSON string that requires expansion and proper indentation for improved readability. export class MyComponent implements OnInit { some:any = JSON.parse('[{"id":"EN","fill":"blue","classb ...

Consolidate multiple generic items into a single entry

In my current project, I am structuring the types for a complex javascript module. One of the requirements is to handle multiple types using generics, as shown in the snippet below: export interface ModelState< FetchListPayload, FetchListR ...

Angular 2 error: "unknown element" issue persists despite exhausting all attempted solutions

Here's a typical scenario where I attempt to incorporate a component from another module : External component : import { Component, ViewEncapsulation, ElementRef, ViewChild, Input, Output, EventEmitter } from '@angular/core'; declare ...

TS2307 Error: The specified module (external, private module) could not be located

I have come across similar queries, such as tsc throws `TS2307: Cannot find module` for a local file . In my case, I am dealing with a private external module hosted on a local git server and successfully including it in my application. PhpStorm is able ...

A Promise is automatically returned by async functions

async saveUserToDatabase(userData: IUser): Promise<User | null> { const { username, role, password, email } = userData; const newUser = new User(); newUser.username = username; newUser.role = role; newUser.pass ...

When changing the dropdown option on a separate page in React/Next JS, all checkboxes show the clicked style as a result of utilizing useState

I have implemented checkboxes for three different categories: "Types", "Price", and "Categories". They function correctly, with data being passed to a separate checkbox component without any issues. The problem arises when I click a checkbox and then inte ...