如果我有以下接口:
interface CustomElementConstructor {
new (...params: any[]): HTMLElement;
}
interface CustomElementRegistry {
define(name: string, constructor: CustomElementConstructor): void;
}
interface Window {
customElements: CustomElementRegistry
}constructor参数被约束为什么类型?从接口定义看,我认为它应该是一个具有构造函数的对象,该构造函数返回类型为HTMLElement的对象。但是对于下面的代码,TypeScript会抛出一个错误(并且源代码确实是无效的):
class X {
constructor(): HTMLElement {
return document.createElement("div") as HTMLElement;
}
}
customElements.define("hi", X);这是因为TypeScript没有为构造函数声明除自身之外的不同返回类型吗?或者,接口中的new值有没有更复杂的东西...?
发布于 2021-07-12 02:05:06
你得到的第一个错误是TS 1093: Type annotation cannot appear on a constructor declaration.。这是因为在class定义中,构造函数总是返回一个类的实例,在本例中是X的一个实例。
这也解释了下一个错误,也就是TS 2345: Argument of type 'typeof X' is not assignable to parameter of type 'CustomElementConstructor'.。构造函数返回X的实例,而X的实例(也称为X类型的对象)没有来自HTMLElement的属性。
我认为您希望将X类定义为HTMLDivElement的子类,因此X的每个实例也是HTMLElement的有效实例,如下所示:
class X extends HTMLDivElement {
constructor() {
super();
}
}
customElements.define("hi", X);https://stackoverflow.com/questions/68338708
复制相似问题