Working with TypeScript: Overriding a Parent Constructor

I am new to TypeScript and currently learning about Classes. I have a question regarding extending parent classes:

When we use the extends keyword to inherit from a parent class, we are required to call the super() method in the child class constructor. However, what if I want to skip the parent constructor or override it?

class Base {
  name: string;
  constructor() {
    name = 'based'
    console.log("Do not display this");
  }
}
 
class Derived extends Base {
  name = "derived";
  constructor(){
    super()
    console.log("My name is " + this.name);
  }
}

const d = new Derived();

[LOG]: "Do not display this"

[LOG]: "My name is derived"

Answer №1

Is it possible to skip the parent constructor or override it?

No, you cannot skip the parent constructor. In fact, constructors for derived classes must include a super call.

However, you can structure your base class in a way that allows for controlling the execution of the constructor based on arguments:

TS Playground

class Base {
  name = 'base';

  constructor (runOptionalCodePath = true) {
    if (runOptionalCodePath) {
      console.log('Dont show that');
    }
  }
}

class Derived extends Base {
  override name = 'derived';

  constructor () {
    super(false);
    console.log(`My name is ${this.name}`);
  }
}

new Derived(); // "My name is derived"
new Base(); // "Dont show that"

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

Is there a counterpart to ES6 "Sets" in TypeScript?

I am looking to extract all the distinct properties from an array of objects. This can be done efficiently in ES6 using the spread operator along with the Set object, as shown below: var arr = [ {foo:1, bar:2}, {foo:2, bar:3}, {foo:3, bar:3} ] const un ...

The data type 'boolean' cannot be assigned to the type 'CaseReducer<ReportedCasesState, { payload: any; type: string; }>'

I recently developed a deletion reducer using reduxjs/toolkit: import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { AppThunk } from "../store"; import { ReportedCase, deleteReportCase } from "../../api/reportedCasesApi"; import history ...

Unable to set value using React Hook Form for Material-UI Autocomplete is not functioning

Currently, I am in the process of constructing a form using React-Hook-Form paired with Material-UI. To ensure seamless integration, each Material-UI form component is encapsulated within a react-hook-form Controller component. One interesting feature I a ...

Developing Angular dynamic components recursively can enhance the flexibility and inter

My goal is to construct a flexible component based on a Config. This component will parse the config recursively and generate the necessary components. However, an issue arises where the ngAfterViewInit() method is only being called twice. @Component({ ...

Zod data structure featuring optional fields

Is there a more efficient way to define a Zod schema with nullable properties without repeating the nullable() method for each property? Currently, I have defined it as shown below: const MyObjectSchema = z .object({ p1: z.string().nullable(), p2 ...

Tips on transferring information to the graphical user interface

Here is my code snippet: signup.post('/signup', urlendcodedParser, async(req: Request, res: Response) => { const username = req.body.username; const password = req.body.password; const age = req.body.age; const email = req ...

What could be causing TypeScript to throw errors regarding the initialState type when defining redux slices with createSlice in reduxToolkit, despite it being the correct type specified?

Here is my implementation of the createSlice() function: import { createSlice, PayloadAction } from "@reduxjs/toolkit"; type TransferDeckModeType = "pipetting" | "evaluation" | "editing"; var initialState: Transfer ...

Converting an array of objects to an array based on an interface

I'm currently facing an issue with assigning an array of objects to an interface-based array. Here is the current implementation in my item.ts interface: export interface IItem { id: number, text: string, members: any } In the item.component.ts ...

I am looking to implement tab navigation for page switching in my project, which is built with react-redux and react-router

Explore the Material-UI Tabs component here Currently, I am implementing a React application with Redux. My goal is to utilize a panelTab from Material UI in order to navigate between different React pages. Whenever a tab is clicked, <TabPanel value ...

Is it possible for a button to be assigned to a variable upon creation, but encounter an error when trying to

const button:Element = document.createElement("button");//This works fine const button:HTMLButtonElement = document.createElement("button");//This works too const button2:Element = document.getElementsByTagName("button");//Why does this give an error? con ...

The issue of HTTP parameters not being appended to the GET request was discovered

app.module.ts getHttpParams = () => { const httpParamsInstance = new HttpParams(); console.log(this.userForm.controls) Object.keys(this.userForm.controls).forEach(key => { console.log(this.userForm.get(key).value) const v ...

Why isn't the customer's name a part of the CFCustomerDetails class?

Currently, I am utilizing the cashfree-pg-sdk-nodejs SDK to integrate Cashfree payment gateway into my application. Upon examining their source code, I noticed that the CFCustomerDetails class does not include the customerName attribute. https://i.stack.i ...

What is the best way to delete previously entered characters in the "confirm password" field after editing the password

Is there a way to automatically remove characters in the confirm password field if characters are removed from the password field? Currently, when characters are entered into the password field, characters can also be entered into the confirm password fiel ...

How can one interpret the act of "passing" an interface to an RxJS Store using angle brackets?

When working with NgRx and typescript, I often come across this syntax within class constructors: import { Store, select } from '@ngrx/store' class MyClass { constructor(private store: Store<AppState>) { this.count$ = store.pipe(sele ...

Next.js is having trouble identifying the module '@types/react'

Every time I attempt to launch my Next.js app using npm run dev, an error notification pops up indicating that the necessary packages for running Next with Typescript are missing: To resolve this issue, kindly install @types/react by executing: np ...

Strategies for implementing searchbar filtering in Ionic3 and Angular5 data manipulation

I'm having trouble displaying product names on my search.html page based on the search bar input. I've tried using the Ionic searchbar component but it's not working. Can anyone help me with this issue? If there's an alternative solutio ...

Tips for avoiding the transmission of className and style attributes to React components

Hey there! I'm working on a custom button component that needs to accept all ButtonHTMLAttributes except for className and style to avoid any conflicts with styling. I'm using TypeScript with React, but I've run into some issues trying to ac ...

In Angular, dynamically updating ApexCharts series daily for real-time data visualization

I am currently working with apexchart and struggling to figure out how to properly utilize the updateseries feature. I have attempted to directly input the values but facing difficulties. HTML <apx-chart [chart]="{ type: ...

Chai expect() in Typescript to Validate a Specific Type

I've searched through previous posts for an answer, but haven't come across one yet. Here is my query: Currently, I am attempting to test the returned type of a property value in an Object instance using Chai's expect() method in Typescript ...

Issues with loading NextJS/Ant-design styles and JS bundles are causing delays in the staging environment

Hey there lovely folks, I'm in need of assistance with my NextJS and Ant-design application. The current issue is only occurring on the stagging & production environment, I am unable to replicate it locally, even by running: npm run dev or npm r ...