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?