Accessing superclass properties from within a mixin with TypeScript declarations

走远了吗. 提交于 2020-03-05 07:35:22

问题


This is a follow up question to Using JavaScript Class Mixins with TypeScript Declaration Files

Given a JavaScript Mixin:

export function Mixin(superclass) {
  return class Consumer extends superclass {
    connectedCallback() {
      super.connectedCallback && super.connectedCallback();
      this.mo = new MutationObserver(console.log)
      this.mo.observe(this)
    }

    classMethod() {
      return true
    }
  }
}

And a TypeScript declaration file:

export declare class Consumer extends HTMLElement {
  public classMethod(): boolean
}

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

declare type ReturnConstructor = new (...args: any[]) => HTMLElement & Consumer

export function Mixin<TBase extends Constructor>(superclass: TBase): TBase & ReturnConstructor;

I'd expect that the class body of the mixin would pick up on the HTMLElement types from the superclass,

however, I receive this error, complaining that the superclass does not implement HTMLElement

error TS2345: Argument of type 'this' is not assignable to parameter of type 'Node'.
  Type 'Consumer' is missing the following properties from type 'Node': baseURI, childNodes, firstChild, isConnected, and 47 more.

  06       this.mo.observe(this);

If I add the following JSDoc to the mixin function,

/** @param {typeof HTMLElement} superclass */
export function Mixin(superclass) { /*...*/ }

the error disappears, but I get a new one instead, claiming that Property 'connectedCallback' does not exist on type 'HTMLElement'.

How shall I annotate the superclass so that it's types transfer?

来源:https://stackoverflow.com/questions/58258115/accessing-superclass-properties-from-within-a-mixin-with-typescript-declarations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!