Typescript - Mixins

TypeScript (and JavaScript) classes support strict single inheritance.

// So you cannot do:
class Tagged {
constructor(private tag: string) {}
}

class Timestamped {
constructor(private timestamp: string) {}
}

class User extends Tagged, Timestamped {} // TS1174: Classes can only extend a single class.

So you can use Mixins if you want to make use of this mechanism


1. Define Constructor type

type Constructor<T = {}> = new (...args: any[]) => T;

2. A mixin that adds a property

function Timestamped<TBase extends Constructor>(Base: TBase) {
return class extends Base {
timestamp = Date.now();
};
}

3. A mixin that adds a property and methods

function Activatable<TBase extends Constructor>(Base: TBase) {
return class extends Base {
isActivated = false;

activate() {
this.isActivated = true;
}

deactivate() {
this.isActivated = false;
}
};
}

4. Use the mixin

class User {
name = '';
}

// User that is Timestamped
const TimestampedUser = Timestamped(User);

// User that is Timestamped and Activatable
const TimestampedActivatableUser = Timestamped(Activatable(User));

const timestampedActivatableUserExample = new TimestampedActivatableUser();
console.log(timestampedActivatableUserExample.timestamp);
console.log(timestampedActivatableUserExample.isActivated);