I would like my class to extends multiple classes. I saw an example using typescript mixins but no example classes have a constructor. I need a class to implement many classes with a constructor, like this:
class Realm {
private _realms: ContractType;
constructor(realms: ContractType) {
this._realms = realms;
}
realmsFunction() {
// do smt...
}
}
class Resource {
private _resources: ContractType;
constructor(resources: ContractType) {
this._resources = resources
}
resourceFunction() {
// do smt else ...
}
}
class Player extends Realm, Resource {
constructor(realms, resources) {
super.Realm(...);
super.Resources(...);
}
}
The only way I found to cleanly do this is (minimal viable example)
class Realm {
private _realms: string;
constructor(realms: string) {
this._realms = realms;
}
realmsFunction() {
// do smt...
}
}
class Resource {
private _resources: string;
constructor(resources: string) {
this._resources = resources
}
resourceFunction() {
// do smt else ...
}
}
class Player {
constructor(realms, resources) {
Object.assign(this, new Realm("realm"), new Resource("resource"));
}
foo() {
this.realmsFunction(); // err: this function doesn't exist
}
}
But typescript complain that this.realmsFunction
or this.resourcesFunction
doesn't exist on this
.
How can I make this error disapear ?
Another solution I found is
class Player {
private _realms: Realms;
private _resources: Resources;
constructor(realms, resources) {
this._realms = new Realms(realms);
this._resources = new Resources(resources);
}
}
This would work just fine, but it's not really using the amazing polymorphism that JS gave us, so I'm not sure it's a good solution or not.
How can I either make the TS error disapear, or find a solution that allow me to inherit many classes with constructor using typescript ?