Using Typescript to inherit from several classes with constructors

I am trying to have my class extend multiple classes, but I haven't been able to find a clean solution. The examples I came across using TypeScript mixins did not include constructors. Here is what I am looking for:

class Realm {
   private _realms: ContractType;
   constructor(realms: ContractType) {
      this._realms =  realms;
   }
   realmsFunction() {
      // do something...
   }
}

class Resource {
   private _resources: ContractType;
   constructor(resources: ContractType) {
      this._resources = resources
   }
   resourceFunction() {
      // do something else ...
   }
}

class Player extends Realm, Resource {
   constructor(realms, resources) {
      super.Realm(...);
      super.Resources(...);
   }
}

The workaround I found (a minimal viable example)

class Realm {
    private _realms: string;
    constructor(realms: string) {
       this._realms =  realms;
    }
    realmsFunction() {
       // do something...
    }
 }
 
 class Resource {
    private _resources: string;
    constructor(resources: string) {
       this._resources = resources
    }
    resourceFunction() {
       // do something else ...
    }
 }
 
 class Player {
    constructor(realms, resources) {
        Object.assign(this, new Realm("realm"), new Resource("resource"));
    }

    foo() {
        this.realmsFunction(); // error: this function doesn't exist
    }
 }

However, TypeScript complains that this.realmsFunction and this.resourcesFunction do not exist on this. Is there a way to resolve this error?

Another solution I came up with is

class Player {
   private _realms: Realms;
   private _resources: Resources;

   constructor(realms, resources) {
      this._realms = new Realms(realms);
      this._resources = new Resources(resources);
   }
}

This solution works fine, but it doesn't fully utilize the polymorphism in JavaScript. I'm unsure if this is the best approach or not.

How can I either get rid of the TypeScript error or find a better solution to inherit multiple classes with constructors in TypeScript?

Answer №1

It is important to note that TypeScript does not support multiple inheritance.

One workaround for this limitation is to utilize composition and interfaces.

interface ContractType {}
interface IRealm {
  realmsFunction: () => void;
}
interface IResource {
  resourceFunction: () => void;
}

class Realm implements IRealm {
  private _realms: ContractType;
  constructor(realms: ContractType) {
    this._realms = realms;
  }
  realmsFunction() {
    // perform actions related to realms...
  }
}

class Resource implements IResource {
  private _resources: ContractType;
  constructor(resources: ContractType) {
    this._resources = resources
  }
  resourceFunction() {
    // perform alternative actions related to resources...
  }
}

class Player implements IRealm, IResource {
  private realm: Realm;
  private resource: Resource;
  constructor(realms, resources) {
    this.realm = new Realm(realms);
    this.resource = new Resource(resources);
  }
  realmsFunction(): void { 
    return this.realm.realmsFunction()
  }
  resourceFunction(): void {
    return this.resource.resourceFunction()
  }
}

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

Working with Files in TypeScript

New to TypeScript and seeking a command to eliminate the file path and extension. For example, if my file is located at ./data/input/myfile.js, how can I extract only "myfile" without the path and extension? ...

The utilization of functions from a implemented interface results in the generation of a 'non-function' error

I recently created an interface that includes variables and a function. However, I encountered an issue when trying to utilize the implemented function for a specific class as it resulted in an 'ERROR TypeError: ...getPrice is not a function" Below ...

Having trouble retrieving a value from the img.onload event handler. A 'boolean' type error is being thrown, indicating it cannot be assigned to type '(this: GlobalEventHandlers, ev: Event) => any'

In my Angular application, I have implemented a method that verifies the size and dimensions of an image file and returns either false or true based on the validation result. Below is the code snippet for this function: checkFileValidity(file: any, multipl ...

What is the best way to filter specific data types when using ngFor in Angular?

As I loop through the array named "fruits," which contains objects of type "FruitService" that I created, I want to display each element. However, when I delete them (I know it's strange, no database involved), they turn into type "undefined" and star ...

Nativescript encountered an error regarding faker: module './address' not found

Currently in the process of learning nativescript, I am experimenting with using faker to generate some data while working with typescript. Here are the versions I am using: Node - 6.9.4 Faker - 3.1.0 Typescript - 2.1.4 Encountered an error which i ...

Typescript navigation and Next.js technology

Currently, I am in the process of learning typescript and attempting to create a navigation bar. However, I encountered an error message stating "Unexpected token header. Expected jsx identifier". I am a bit puzzled by this issue. Could someone kindly pro ...

Mastering the art of correctly utilizing splice and slice

I'm having trouble identifying the issue in my code. Despite reading numerous articles on slice and splice, I am unable to achieve the desired outcome in my Angular project (not using both methods simultaneously). The results are not as expected. Belo ...

Wildcard routes taking precedence over other defined routes

Currently, I'm developing a Node.js server utilizing Express.js and Typescript. Within my project structure, there is a folder named "routes" where I store .ts files containing route definitions. An example of a route file might appear like this: impo ...

Is AWS CDK generating nested cdk.out directories during synthesis?

Whilst working on my AWS CDK project for educational purposes, I found myself immersed in learning TypeScript, node.js, npm, and all related concepts simultaneously. Despite the mishap that occurred, requiring me to restart from the Github repository rathe ...

What could be causing the OnInit lifecycle hook to fail to execute properly?

I'm having trouble with this code. Every time I run it, the console throws a type error saying it can't read property sort. Does anyone have any ideas on how to fix this? import { Component, OnInit, Input } from '@angular/core'; impor ...

When the code is run, does it also create a class object since the class is also a type of object?

class Example: def show_text(): print('Hello') Since classes are also objects of type, does the creation of a class object occur when the code above is run? If so, what is the method to confirm this? ...

Definition in Typescript: The term "value is" refers to a function that takes in any number of arguments of

export function isFunction(value: any): value is (...args: any[]) => any { return typeof value === 'function'; } What is the reason behind using value is (...args: any[]) => any instead of boolean ? ...

Creating web components with lit-element, leveraging rollup, postcss, and the tailwind framework for packaging

I have been attempting to package a functional web component that was developed using the lit-element/lit-html with the tailwind framework utilizing the postcss plugin from the rollup packager. Upon conducting a rollup, I discovered the compiled js and ht ...

Assigning enum type variable using string in TypeScript

How can I dynamically assign a value to a TypeScript enum variable? Given: enum options { 'one' = 'one', 'two' = 'two', 'three' = 'three'} let selected = options.one I want to set the variable " ...

The Heart of the Publisher-Subscriber Design Paradigm

After reading various online articles on the Publisher-Subscriber pattern, I have found that many include unnecessary domain-specific components or unreliable information inconsistent with OOP standards. I am seeking the most basic and abstract explanatio ...

Why am I unable to use a string as the src in next/image component?

After importing the Image module with the code import Image from "next/image";, I encountered an error that states: The type '{ src: string; }' cannot be assigned to type 'IntrinsicAttributes & ImageProps'. The type &apo ...

The stacked bar chart in Apex is not displaying correctly on the x-axis

Currently, I am utilizing the Apex stacked bar chart within my Angular 16 project. In this scenario, there are 4 categories on the x-axis, but unfortunately, the bars are not aligning correctly with the x-axis labels. The data retrieved from my API is as ...

Prevent methods from being called in a Typescript class after they have already

I encountered a scenario where I need to exclude certain methods from the return type of a class method once they have been called. Consider a class named Setup with methods step1, step2, and step3. class Setup { step1() { return this; } ...

Exploring TypeScript and React: Redefining Type Definitions for Libraries

As I transition from JSX to TSX, a challenge has arisen: My use of a third-party library (React-Filepond) This library has multiple prop types The provided types for this library were created by an individual not affiliated with the original library (@ty ...

Issue when transferring properties of a component to a component constructed Using LoadingButton MUI

Check out my new component created with the LoadingButton MUI: view image description here I'm having issues passing props to my component: view image description here Dealing with a TypeScript problem here: view image description here I can resolv ...