How can one implement inheritance from multiple classes using Generics?

I've been stuck on this problem for days and feel like I've exhausted my TypeScript skills. Any help would be greatly appreciated.

Although I have complex types, I'll try to simplify them for clarity.

Playground link

Imagine I have two classes, Score and Metric, each with two derived classes that need to implement different methods. The scores can inherit from a base class, but the Metrics must inherit from external classes that I don't own.

I tried using Mixins to define common methods in a class factory and apply constructors based on the implementations, but I'm struggling to get it to work.

So far, I've used interfaces A and B to distinguish between functionalities or as generic kinds extending A or B where shared functions exist.

Now, however, I need to use distinct constructors based on implementation rather than just types. While I don't require access to additional methods of derived classes, I must create objects at runtime inheriting the correct method from either A or B. It seems there might not be a solution for this, prompting me to consider alternative inheritance patterns beyond A and B.

If someone could verify if there's a workaround or offer a better abstraction pattern, I'd be extremely grateful.

Answer №1

After exploring various options, I eventually settled on implementing this code. While Kellys provided a helpful hint, I found that for my specific situation of dealing with multiple patterns where the primary difference lies in the "Kind," this approach worked more effectively. By passing an object of type Kind into the constructor (which is suitable for me as I can handle it in the constructors of subclasses)

interface X { isX:true}
interface Y { isY:true}

class BaseX {
    update(){/**do something */}
}

class BaseY {
    update(){/**do something else */}
}

interface Base{
    update:()=>void;//the methods here should be accessible when referencing a generic metric
}

type BaseConstructor = new (...args:any[])=>Base

function MetricFactory<MetricType extends BaseConstructor>(BaseZ:MetricType){
    return class extends BaseZ{
        commonMethod(){}
    }
}

class MetricY extends MetricFactory(BaseY){}
class MetricX extends MetricFactory(BaseX){
    someAdditionalMethod(){return this.commonMethod()}
}
function Metric<Kind extends X|Y>(kind:Kind) {
    return (kind as X).isX !== undefined ? new MetricX(): new MetricY() 
}

class Grade<Kind extends X|Y>{
    constructor(kind: Kind) {
        this.genericMetric = Metric(kind) as Kind extends X ? MetricX: MetricY
    }
    genericMetric: Kind extends X ? MetricX: MetricY
}

class GradeX extends Grade<X>{
    constructor(){super({isX:true})}
}

let myGrade = new GradeX()

myGrade.genericMetric.update() //does something
myGrade.genericMetric.commonMethod() //performs common action
myGrade.genericMetric.someAdditionalMethod() //executes additional step

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

When I specify the type for the function parameter, an error occurs when I attempt to execute the function

When I assign a generic type to the function parameter and try to call the function, an error message pops up stating "This expression is not callable. Type unknown has no call signature." function a() { return 'abc' } function fun<T>(x: T ...

What is the TypeScript type for a delayed async function call using setTimeout()?

So, I have two functions related to fetching credentials from an external API. The first function simply fetches the credentials: const fetchCredentials= async () => { return await fetch(/* url and params */); }; The second function is a bit mo ...

Arranging a group of objects in Angular2

I am facing challenges with organizing an array of objects in Angular2. The structure of the object is as follows: [ { "name": "t10", "ts": 1476778297100, "value": "32.339264", "xid": "DP_049908" }, { "name": "t17", "ts": 14 ...

Looking to extract the expiration date from an x509 certificate?

I am currently engaged in a project that involves retrieving and displaying certificate information from an Azure integration account using Angular/Typescript. One of the requirements is to show the decoded public certificate to users to extract important ...

Using a class object as a parameter in a template function in the C++ programming language

I have created a template function that looks like this: template<class T> string convertToString(T value) { ostringstream ss; if (is_same<T, Student>::value) { ss << value.getFirst() << ":" << value.getL ...

Could someone provide a detailed explanation of exhaustMap in the context of Angular using rxjs?

import { HttpHandler, HttpInterceptor, HttpParams, HttpRequest, } from '@angular/common/http'; import { Injectable } from '@core/services/auth.service'; import { exhaustMap, take } from 'rxjs/operators'; import { Authe ...

Cannot access Microsoft Graph without user - the 'grant_type' is not present in the body

I am eager to dive into Microsoft Azure and Graph by creating a simple application that will utilize the Graph API as a background worker. Although I currently only have a demo account, I believe this should not pose a problem. I am following along with t ...

Ways to mock a static method within an abstract class in TypeScript

Having a difficult time testing the function Client.read.pk(string).sk(string). This class was created to simplify working with dynamoDB's sdk, but I'm struggling to properly unit test this method. Any help or guidance would be greatly appreciate ...

The process of switching from timestamp to date varies depending on whether you are working locally or on a server

Currently, I am in the process of developing an app using Firebase as the server and Flutter for the frontend. The situation I am facing is that when I upload a new document with a timestamp containing the current time in this format: "timestamp": DateTim ...

The shift from es6 to commonJs in Angular modules has far-reaching implications

My attempt to incorporate FileSaver into my app led me to use the following command: import filesaver = require('filesaver'); However, this resulted in the error message: Import assignment cannot be used when targeting ECMAScript 2015 module ...

Error encountered in typescript when trying to implement the Material UI theme.palette.type

Just starting out with Material UI and TypeScript, any tips for a newcomer like me? P.S. I'm sorry if my question formatting isn't quite right, this is my first time on Stack Overflow. https://i.stack.imgur.com/CIOEl.jpg https://i.stack.imgur.co ...

Unable to locate the reference for 'bootstrap'

After trying to implement Bootstrap toast in an Angular Component, the following error message is displayed: "Cannot find name 'bootstrap'" Here is the HTML code similar to the Bootstrap documentation: <div class="toast" r ...

What steps should I take to successfully compile my Typescript Webpack project without any errors?

Currently, I am attempting to convert only two .js files into .ts files within my webpack node.js project and then compile them (actions.ts and flux.ts). When I execute the command: webpack --progress --colors I encounter the following errors: 'use ...

Tips for including a dash or hyphen in an input field after two digits in Angular 4

Struggling to format the date of birth input with dashes manually when entered by the user. The desired output should resemble "08-18-2019," but I'm having difficulty achieving this. public dateOfBirth: { year: number; month: number; day: number }; ...

grunt error TS1005: missing semicolon

Currently, I am working with Angular and TypeScript to interact with a REST webservice. Since I am still new to TypeScript, my issue might be basic or my approach could be incorrect. The problem I am facing is receiving an error TS1005: ';' expec ...

Generate a new data structure by pairing keys with corresponding values from an existing

Imagine having a type named Foo type Foo = { a: string; b: number; c: boolean; } Now, I am looking to create a type for an object containing a key and a value of a designated type T. The goal is for the value's type to be automatically determin ...

Tips for showing JSON information in Nativescript

How can I display all values in a page using the provided JSON data? res { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "sensors": [ { "serial": "sensor1", "id": "1" }, ...

How to modify the background color within the mat-menu-panel

Incorporating angular 9 and less into my current project, I have encountered an issue with a mat-menu-panel where my mat-menu-item is located. While I have successfully changed the color of my mat-menu-item, I am now faced with the challenge of changing th ...

What is the process for sending JSON data in a file to a django rest api?

Currently, I am using Angular on the front-end and Django Rest on the back-end. I have encountered a scenario where I need to create a complex model. Despite considering other simpler solutions, I believe that using JSON to pass the files can streamline th ...

The Add New Item button on the To-Do List is not working and fails to add any new items

As a newcomer to React, I am struggling to pinpoint the source of the issue in my code. I suspect it has something to do with a function call, and despite my attempts to debug the problem, I have been unsuccessful. I am unsure of any other tools or methods ...