Использование классов классов JavaScript с файлами декларации TypeScript - PullRequest
2 голосов
/ 06 октября 2019

Мне нужна помощь с использованием классов mixins в файлах объявлений. В частности, когда метод определен в миксине, машинопись не берет его в теле смешанного класса:

В моем случае я применяю два миксина. Первый mixin - NotifyingElementMixin - предоставляет метод с именем notify, и именно этот метод не применяется к телу смешанного класса

notifying-element-mixin.js

export const NotifyingElementMixin = superclass =>
  class NotifyingElement extends superclass {
    /**
     * Fires a `*-changed` event.
     *
     * @param  {string}     propName Name of the property.
     * @param  {any} value  property value
     * @protected
     */
    notify(propName, value) {
      this.dispatchEvent(
        new CustomEvent(`${propName}-changed`, {
          detail: { value },
        })
      );
    }
  };
};

notifying-element-mixin.d.ts

export declare class NotifyingElement {
  public notify(propName: string, value: any): void
}

export function NotifyingElementMixin<TBase extends typeof HTMLElement>
(superclass: TBase): TBase & NotifyingElement;

Второй миксин предоставляет другие свойства и методы, но ради этого вопроса я упростил реализацию

apollo-query-mixin.js

export const ApolloQueryMixin = 
  superclass => class extends superclass {
    data = null;
    is = 'Query';
  };

apollo-query-mixin.d.ts

export declare class ApolloQuery<TCacheShape, TData, TVariables, TSubscriptionData = TData> {
  data: null
  is: string
}

type Constructor<T = HTMLElement> = new (...args: any[]) => T;
export function ApolloQueryMixin<TBase extends Constructor, TCacheShape, TData, TVariables>
(superclass: TBase): ApolloQuery<TCacheShape, TData, TVariables> & TBase;

Наконец, я хочу экспортировать класс, который применяет оба миксина и предоставляет свои собственные методы. также. Здесь я сталкиваюсь с проблемами

apollo-query.js

class ApolloQuery extends NotifyingElementMixin(ApolloQueryMixin(HTMLElement)) {
  /**
   * Latest data.
   */
  get data() {
    return this.__data;
  }

  set data(value) {
    this.__data = value;
    this.notify('data', value);
  }
  // etc
}

apollo-query.d.ts

import { ApolloQueryMixin } from "./apollo-query-mixin";
import { NotifyingElementMixin } from "./notifying-element-mixin";

export declare class ApolloQuery<TBase, TCacheShape, TData, TVariables>
extends NotifyingElementMixin(ApolloQueryMixin(HTMLElement)) {}

Когда я компилирую это, илииспользуя мою IDE, я получаю сообщение об ошибке:

error TS2339: Property 'notify' does not exist on type 'ApolloQuery'.

Как мне заставить машинописный текст забрать мои унаследованные методы в теле смешанного класса?

1 Ответ

1 голос
/ 06 октября 2019

Вот шаблон миксина, который я использую, я думаю, ключом является конструктор возврата:

import { LitElement, property } from "lit-element";

type Constructor = new (...args: any[]) => LitElement;

interface BeforeRenderMixin {
  beforeRenderComplete: Boolean;
}

type ReturnConstructor = new (...args: any[]) => LitElement & BeforeRenderMixin;

export default function<B extends Constructor>(Base: B): B & ReturnConstructor {
  class Mixin extends Base implements BeforeRenderMixin {
    @property({ type: Boolean })
    public beforeRenderComplete: boolean = false;

    public connectedCallback() {
      super.connectedCallback();
      if (!this.beforeRenderComplete)
        this.beforeRender().then(() => (this.beforeRenderComplete = true));
    }

    public async beforeRender() {
      return;
    }

    public shouldUpdate(changedProperties: any) {
      return this.beforeRenderComplete && super.shouldUpdate(changedProperties);
    }
  }

  return Mixin;
}

, который генерирует:

import { LitElement } from "lit-element";
declare type Constructor = new (...args: any[]) => LitElement;
interface BeforeRenderMixin {
    beforeRenderComplete: Boolean;
}
declare type ReturnConstructor = new (...args: any[]) => LitElement & BeforeRenderMixin;
export default function <B extends Constructor>(Base: B): B & ReturnConstructor;
export {};
...