【问题标题】:Accessing superclass properties from within a mixin with TypeScript declarations使用 TypeScript 声明从 mixin 中访问超类属性
【发布时间】:2020-02-04 01:46:34
【问题描述】:

这是Using JavaScript Class Mixins with TypeScript Declaration Files的后续问题

给定一个 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
    }
  }
}

还有一个 TypeScript 声明文件:

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;

我希望 mixin 的类主体会从 superclass 中获取 HTMLElement 类型,

但是,我收到此错误,抱怨 superclass 没有实现 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);

如果我将以下 JSDoc 添加到 mixin 函数中,

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

错误消失了,但我得到了一个新错误,声称Property 'connectedCallback' does not exist on type 'HTMLElement'.

我应该如何注释超类以便它的类型转移?

【问题讨论】:

    标签: typescript mixins .d.ts


    【解决方案1】:

    TypeScript 中的 Mixin 支持非常糟糕。 :(

    但是,基于你已经做过的,你可以做的是使用 JSDoc

    /** @param {PossibleCustomElementConstructor} superclass */
    

    你还要定义的地方

    interface PossibleCustomElement extends HTMLElement {
      connectedCallback?(): void
      disconnectedCallback?(): void
      attributeChangedCallback?(attr: string, oldVal: string | null, newVal: string | null): void
      adoptedCallback?(): void
    }
    
    interface PossibleCustomElementConstructor {
      new (...args: any[]): PossibleCustomElement
      observedAttributes?: string[]
    }
    

    关于 Mixin 问题,我已经打开了a bunch of them,看来他们并不急于修复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-25
      • 2019-10-03
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-18
      相关资源
      最近更新 更多