【发布时间】: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