Extending type when extending an ES6 class with a TypeScript decorator

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.


To supplement jcalz response, going back to the definition of the Decorator Pattern, it does not change the interface/contracts of its target. It's not just terminology. TypeScript decorators share similarities with Java annotations and .NET attributes which are aligned with the fact not to change the interface: they just add metadata.

Class mixin is a good candidate to solve your question. But it's better not to use "decorator" in its name in order to avoid confusion.