Is it possible to pass parameters from a base class's constructor to a child class?

I'm facing an issue with my base (generic) classes where the properties are initialized in the constructor. Whenever I try to extend these classes to create more specific ones, I find myself repeating the same parameters from the base class's constructor just to pass them to super. It feels ineffiecient to constantly duplicate these properties every time I extend the class. Is there a better way to handle this? Maybe some approach to automatically inherit the parent class's constructor parameters?

For instance, take a look at this code snippet - notice how in Programmer's constructor, I have to redundantly mention name, age, and height again only to pass them to super:

class Person {
    name: string;
    age: number;
    height: number;

    constructor(name: string, age: number, height: number) {
        this.name = name;
        this.age = age;
        this.height = height;
    }
}

class Programmer extends Person {
    languages: string[];

    constructor(name: string, age: number, height: number, languages: string[]) {
        super(name, age, height);

        this.languages = languages;
    }
}

Answer №1

If you can't directly inherit, you have the option to reference the parameter by utilizing ConstructorParameters and then spread them in your descendant constructor. Just remember that any new parameters should be added at the beginning:

class Animal {
    type: string;
    color: string;

    constructor(type: string, color: string) {
        this.type = type;
        this.color = color;
    }
}

class Dog extends Animal {
    breed: string[];

    constructor(breed: string[], ...a: ConstructorParameters<typeof Animal>) {
        super(...a);

        this.breed = breed;
    }
}

new Dog(["Golden Retriever"], "", "brown") // Since version 3.4, you will see actual parameter names in the IntelliSense instead of just ...a 

This approach may not be considered the ideal design. If dealing with a large number of parameters, it might be more beneficial to define an interface and pass that in instead. Alternatively, consider using a mapped type to extract relevant fields.

Answer №2

Since the base class Person requires parameters like name, age, and height for initialization, the extended class Programmer will also need these constructor arguments.

If you find yourself in a situation where there are multiple arguments needed, consider using a creation pattern such as the builder pattern to instantiate objects of the extended class.

To have a no-argument constructor, you can make the super constructor parameters optional.

class Person {
  name: string;
  age: number;
  height: number;

  constructor(name?: string, age?: number, height?: number) {
      this.name = name;
      this.age = age;
      this.height = height;
  }
}


class Programmer extends Person {
  languages: string[];

  constructor(languages: string[]) {
      super();

      this.languages = languages;
  }
}

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

I have a question about TypeScript mapped types. Why is it not possible to retrieve the keys of a union of interfaces?

Below is the code snippet that I am working with: interface Data { A: { a1: string; a2: string; }; B: { b1: number; b2: string; }; } type TransformDataKey<V extends string, T extends string> = `--${V}-${T}`; type TransformDa ...

What are some creative ways to emphasize certain dates?

Is there a way to customize mui-x-date-pickers to highlight specific days from a Date array with green filled circles around them? I am using new Date and wondering how to achieve this effect. Below is the code snippet I am currently working with: <Dat ...

Unlocking the Power of Typescript and ReactJS: Maximizing Efficiency with Previous State

I'm encountering difficulties implementing the previous state in React 18 with Typescript version 4.8.3. Here is my refreshToken code and I'm receiving the following error: Value of type '(prev: any) => any' has no properties in c ...

Angular 11 along with RxJS does not support the combineLatest method in the specified type

Hey there, I'm currently working on utilizing the combineLatest operator to merge two streams in Angular, but I keep encountering an error message stating that "combineLatest does not exist on type". I've attempted to move the code into a .pipe() ...

ngif directive does not function properly when subscribe is utilized in ngOnInit

this is the unique component code import { Component, OnInit } from '@angular/core'; import { Subscription } from 'rxjs'; //import { Item } from '../item/item.model'; import { CartItem } from './cart-item.model'; imp ...

Separate an array in TypeScript based on the sign of each number, and then replace the empty spaces with null objects

Hey, I'm facing a little issue, I have an Array of objects and my goal is to split them based on the sign of numbers. The objects should then be dynamically stored in different Arrays while retaining their index and getting padded with zeros at the b ...

When employing CDK to configure an SNS topic Policy Statement with actions limited to ["sns:*"], the CloudFormation output may display a warning message stating "Policy statement action is not within the service scope."

Encountering an issue when attempting to reference all SNS actions with * in CDK. const MyTopicPolicy = new sns.TopicPolicy(this, 'MyTopicSNSPolicy', { topics: [MyTopic], }); MyTopicPolicy.document.a ...

The dropdown cannot be disabled because it is being passed as an input parameter

We are currently utilizing PrimeNG along with Angular 15. Scenarios: According to the requirements, we need the ability to disable the PrimeNG dropdown control based on a selection. Problem: The disabled property of <p.dropdown> is not functioning ...

Steps for storing API information in localStorage:1. Retrieve the API data

My app is running sluggish due to the excessive API calls for information retrieval. To optimize performance, I want to create a unified object containing all the data that can be shared across pages and accessed from localStorage, thus enhancing the app ...

The issue with Vuex and Typescript is that when using mutation object payloads, they are consistently undefined

Every time I run my code, the object payload I'm passing as a secondary parameter to my Vuex mutation method ends up being undefined. Both my Vuex and component files are coded in TypeScript. When looking at my index.ts file for my Vuex store (where ...

lint-staged executes various commands based on the specific folder

Within my project folder, I have organized the structure with two subfolders: frontend and backend to contain their respective codebases. Here is how the root folder is set up: - backend - package.json - other backend code files - frontend - p ...

Set the default requests header in Ionic 3 using data stored in Ionic Storage

This particular issue is related to retrieving a value from local storage. I am trying to set the default header (Authorization token) for all requests, but I can't seem to find a solution that works efficiently. Most of the resources available only e ...

Issues arise when attempting to include the src attribute within the template tag in a Vuejs and Laravel project

After starting a project with Vuejs and Laravel using Laravel Mix, I encountered an issue. When attempting to split my component into separate files and load them in the .vue file as follows: <template src="./comp.html"></template> &l ...

Is NATS.io compatible with React Native?

Struggling with integrating nats.io into a React Native project using Typescript has presented many challenges. Is there a way to successfully incorporate it without having to modify node_modules of nats (such as changing the "fs" import to "react-native-f ...

Passing data from ModalService to a component

Currently, I am attempting to utilize the ngx-bootstrap-modal in order to transfer data from a modal service to a modal component. While reviewing the examples, it is suggested to use the following code: this.modalService.show(ModalContentComponent, {init ...

How can Angular display an alert when no items are visible?

I want to display a message saying "Item doesn't exist" when the item is not found. Suppose this is my list: user 0 user 1 user 2 The following code displays the list above: <ng-container *ngFor="let user of users | async; let i = index"> ...

Exploring Parquet Files with Node.js

Looking for a solution to read parquet files using NodeJS. Anyone have any suggestions? I attempted to use node-parquet but found it difficult to install and it struggled with reading numerical data types. I also explored parquetjs, however, it can only ...

Furnish an item for a particular service

I am currently attempting to utilize a service created by another individual (github). This particular service requires a configuration to be passed to it. As stated in the repository: To configure Neo4jSettings in your bootstrap: provide('Neo4jSet ...

The outcome from using Array.reduce may not always match the expected result

After discovering an unexpected behavior in Typescript's type-inference, I suspect there may be a bug. Imagine having a list of the MyItem interface. interface MyItem { id?: string; value: string; } const myItemList: MyItem[] = []; It's ...

Can you use TypeScript to define generic React functional components?

I am looking to add annotations to a generic in a React functional component like the following: import React, {useEffect, useState} from "react"; interface PaginatedTableProps{ dataFetcher: (pageNumber: number) => Promise<any>, columnNames: ...