I found a solution to implement kind-of multiple heritage (really cascades it) but it's worth taking a look.
Supose you have a class Base with a few properties and methods:
class Base {
tableName = 'My table name';
hello(name) {
return `hello ${name}`;
}
}
And you want a class to extend Base but you also have defined some properties you want to reuse. For that will do the following function:
type Constructor<T = {}> = new (...args: any[]) => T;
function UserFields<TBase extends Constructor>(Base: TBase) {
return class extends Base {
name: string;
email: string;
};
}
Now we can do a class that extends Base and extends UserFields and typescript language service will find properties from both classes. It emulates a multiple heritage but it's really a cascade.
class User extends UserFields(Base) { }
const u = new User();
u.tableName = 'users'; // ok
u.name = 'John'; // ok
By this way you could reuse the UserFields function with any other classes.
A clear example of that is if you want to expose the User object on client side as a "clean" object and have the fields available and then you have a UserDb object with connections to database and any other server side methods can have the same fields too. We only define the database fields once!
Another good thing is you could chain mixins mixin1(mixin2....(Base)) to have as many attributes as you want to have in the same class.
Everybody is expecting the decorator attributes to be visible by typescript, but meanwhile is a good solution.
UserFields
function work but would suggest the following:function UserFields<T extends new (...args: any[]) => {}>(constructor: T) { return class extends constructor { name: string; email: string; } }
– Personnel