Contrasting Compositions with Generics

Let's consider a scenario where we have an abstract class A and three concrete classes that inherit from it: A1, A2, and A3. There is also another hierarchy tree with an abstract class B and three concrete classes B1, B2, and B3. Each concrete class A needs to hold a list of objects of the corresponding B class. For example, A1 holds a list of B1 objects. What would be the optimal solution for this situation:

  1. One approach could be to make A a generic class and have it hold a generic list of T which extends B, like so:

    abstract class A<T extends B> {
        protected arr: Array<T extends B>
    }
    

    This way, we can declare each A class as follows:

    class A1 extends A<B1>
    
  2. Alternatively, we can use composition in the following manner:

    class A1 extends A {
        private arr: Array<B1>
    }
    

Answer №1

If you find yourself with multiple classes containing similar code but differing only in the type of object they use, generics may be the way to go. For example, if classes A1, A2, A3 all share functionality but vary in the type of B object, generics could streamline your code. If this isn't the case, consider using composition instead as there may not be a strong reason for utilizing generics.

Answer №2

The second option is my preference! Utilizing generic classes becomes necessary when you want certain methods and functionalities to be implemented on various objects regardless of their specific type. However, it wouldn't be considered good design to declare a class as generic solely to address a composition issue!

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

Angular 2 select does not recognize the selected option

In my Angular 2 code, I am using ngFor to populate a dropdown with options. I want a specific option at a certain index to be selected by default. Currently, I tried using [attr.selected]="i == 0" but it ends up selecting the last option instead of the fi ...

Obtaining Input Field Value in Angular Using Code

How can I pass input values to a function in order to trigger an alert? Check out the HTML code below: <div class="container p-5 "> <input #titleInput *ngIf="isClicked" type="text" class="col-4"><br& ...

Tips for handling undefined values in observable next methods to return a default error message

I sent a request over the network and received a response. Whenever I encounter an undefined value in the response, I want to return a default error message. The response may contain multiple levels of nested objects. Is there a way to replace the if else ...

Setting the ariaLabel value in TypeScript is a straightforward process that involves defining the

In my TypeScript React application, I am attempting to dynamically set the ariaLabel value. However, ESLint is flagging an error: Property 'ariaLabel' does not exist on type 'HTMLButtonElement'. I have tried various types but none of t ...

Obtain the combination of values within an array object

I am attempting to write the specifications for a function that can take records of any structure and convert the values into a discriminated union. For example: const getKeys = <T extends {key: string}>(items: T[]): T['key'] => { // ...

Unable to utilize material tabs in this situation

Discovering the material tabs feature at https://material.angular.io/components/tabs/api#MatTab got me excited to implement it in my project. After adding the suggested import, I encountered an issue where I couldn't find the module "@angular/materia ...

Creating a different type by utilizing an existing type for re-use

Can you help me specify that type B in the code sample below should comprise of elements from interface A? The key "id" is mandatory, while both "key" and "value" are optional. interface A { id: string; key: string; value: string | number; } /** ...

Extract keys from a list of interface keys to create a sub-list based on the type of value

Issue Can the keys that map to a specified value type be extracted from a TypeScript interface treated as a map? For example, consider the WindowEventMap in lib.dom.d.ts... interface WindowEventMap extends GlobalEventHandlersEventMap, WindowEventHan ...

Activate TypeScript EMCAScript 6 support for Cordova projects in Visual Studio

I am interested in utilizing the async/await feature of TypeScript in my VS2015 Cordova project. I have updated "target": "es6" in tsconfig.json Although there are no errors shown in intellisense, I encounter the following error while building the project ...

Importing configuration file in CRA Typescript with values for post-deployment modifications

I am currently working on a React app that utilizes Create React App and Typescript. My goal is to read in configuration values, such as API URLs. I have a config.json file containing this data, here's a sample snippet with placeholder information: { ...

When executing prisma generate, an error of TypeError is thrown stating that the collection is

While using typescript with Prisma, I encountered an issue when trying to run prisma generate, as it kept throwing the following error: TypeError: collection is not iterable. at keyBy (/node_modules/@prisma/client/generator-build/index.js:57685:21) at ...

Ways to Halt observable.timer in Angular 2

As I work on Angular2's Component, I am currently implementing the following functions: export class MypageEditComponent { ngOnInit() { this.timer = Observable.timer(100, 100); this.timer.subscribe(t => { this.setFormData(); } ...

Generating a custom type in Typescript based on specific array keys

Imagine I have a structure like this: export interface MyObject { id: number title: string } and then I create an array as shown below: const myArray: MyObject[] = [ { id: 2358, title: 'Item 1' }, { id: 85373, title: &a ...

Is there a method to improve type inference in vscode?

Recently, I created a component with a click handler that looks like this: onClick={(e) => { e.stopPropagation(); }} It seems clear to me, but then the Typescript compiler complains that it's not a valid signature for onClick, which actually a ...

Toggle Button in Angular upon Form Changes

I am currently working on a bug that involves preventing users from saving data if they have not entered any information in the form. The form structure is as follows: private buildAddressPopupForm() { this.form = this.fb.group({ roles: [''], ...

Tips for navigating the material ui Expanded attribute within the Expansion Panel

After looking at the image provided through this link: https://i.stack.imgur.com/kvELU.png I was faced with the task of making the expansion panel, specifically when it is active, take up 100% of its current Div space. While setting height: 100% did achi ...

What is the best way to handle an OR scenario in Playwright?

The Playwright documentation explains that a comma-separated list of CSS selectors will match all elements that can be selected by one of the selectors in that list. However, when I try to implement this, it doesn't seem to work as expected. For exam ...

There seems to be an issue with Material-UI and TypeScript where a parameter of type 'string' does not have an index signature in the type 'ClassNameMap<"container" | "navBar" | "section0">'

My current project is encountering a TS Error stating "(No index signature with a parameter of type 'string' was found on type 'ClassNameMap<"container" | "navBar" | "section0">'.)" The code below is used to assign styles to vari ...

Navigating through different components in Angular 4 using a service for routing

Encountering an issue while connecting my Angular 4 and REST application with a service. Here's the error message: compiler.es5.js:1694 Uncaught Error: Can't resolve all parameters for TypeaheadComponent: (?, [object Object], [object Object]). ...

Why is my root page not dynamic in Next.js 13?

I am currently working on a website using Next.js version 13.0. After running the next build command, I noticed that all pages are functioning properly except for the root page. The issue is that it's being generated as a static page instead of dynami ...