Typescript mixin с защищенным доступом - PullRequest
0 голосов
/ 20 февраля 2020

У меня есть следующие настройки mixin. Миксин под названием Activatable, которому нужен доступ к защищенным членам User.

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

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

    activate() {
      this.isActivated = true;
      this.deactivate();
    }

    deactivate() {
      this.isActivated = false;
    }

    /**
     * In order to access the protected members of User, I needed to
     * add `this` to the args
     */
    test(this: User) {
      this.me = "bo";
      // this method cannot access any other method in the mixin
    }
  };
}

class User {
  name: string;
  protected me: string;

  constructor(name: string) {
    this.name = name;
    this.me = "hi";
  }
}

const ActivatableUser = Activatable(User);

// Instantiate the new `ActivatableUser` class
const user = new ActivatableUser("John Doe");

// Initially, the `isActivated` property is false
console.log(user.isActivated);

// Activate the user
user.activate();
user.test();

// Now, `isActivated` is true
console.log(user.isActivated);

Чтобы получить доступ к защищенным и закрытым членам (см. test()), мне нужно было использовать this:User как часть подписи. Недостатком подхода является то, что test() не может больше обращаться к другим методам Activatable mixin.

Я бы предпочел не давать имени возвращенному выражению класса имя и использовать as для преобразования this для экземпляра миксина.

Поскольку я знаю, что этот миксин будет использоваться только для класса User, есть ли способ, которым я могу включить эту информацию как часть определения Activatable? Так что мне не нужно использовать this:User как часть сигнатуры метода?

См. Playground Link

Спасибо всем

...