Mixins
class User extends Tagged, Timestamped { // ERROR : no multiple inheritance
}// Ніобхідно для всіх міксінов
type Constructor<T = {}> = new (...args: any[]) => T;
////////////////////
// Приклад mixins
////////////////////
// Мixin який додає властивість
function Timestamped<TBase extends Constructor>(Base: TBase) {
return class extends Base {
timestamp = Date.now();
};
}
// Мixin який додає властивість та методи
function Activatable<TBase extends Constructor>(Base: TBase) {
return class extends Base {
isActivated = false;
activate() {
this.isActivated = true;
}
deactivate() {
this.isActivated = false;
}
};
}
////////////////////
// використання
////////////////////
// Простий class
class User {
name = '';
}
// User that is Timestamped
const TimestampedUser = Timestamped(User);
// User that is Timestamped and Activatable
const TimestampedActivatableUser = Timestamped(Activatable(User));
////////////////////
// Использование расширеного classes
////////////////////
const timestampedUserExample = new TimestampedUser();
console.log(timestampedUserExample.timestamp);
const timestampedActivatableUserExample = new TimestampedActivatableUser();
console.log(timestampedActivatableUserExample.timestamp);
console.log(timestampedActivatableUserExample.isActivated);
Take a constructor
Extend the class and return it
Last updated