【发布时间】:2019-10-23 02:13:58
【问题描述】:
我有一个名为 Parent 的基类:
class Parent {
static elType = window.Element
el: InstanceType<typeof Parent['elType']>
constructor(input: Element) {
let ctor = this.constructor as typeof Parent
if (input instanceof ctor.elType) {
this.el = input
} else {
throw new Error()
}
}
}
仅当input 是构造函数中指定的elType 的实例时,它才允许创建实例。如果检查通过,则将实例成员 el 设置为 input。
然后,我想创建一个只允许HTMLElement(扩展Element)输入的子类:
class Child extends Parent {
static elType = window.HTMLElement
}
但是,实例成员 el 未正确设置为 HTMLElement。还是Element:
let foo = null as unknown as HTMLElement
let ch = new Child(foo)
// Property 'offsetLeft' does not exist on type 'Element'.
ch.el.offsetLeft
我认为问题在于:
el: InstanceType<typeof Parent['elType']>
我将el的类型设置为Parent的elType类型,即Element,不受Child的静态elType的影响。我的问题是 - 我怎样才能使它工作?我需要一些技巧,例如:
el: InstanceType<typeof {{ current class }}['elType']>
在the playground 中查看。
我知道我可以通过在Child 中明确声明el 来解决它:
class Child extends Parent {
static elType = window.HTMLElement
el: HTMLElement
}
但我想避免这种情况,因为它是多余的。 el 应该始终是 static elType 的实例类型。
【问题讨论】:
标签: typescript