【问题标题】:What does the new keyword mean in a interface界面中的new关键字是什么意思
【发布时间】:2021-07-11 17:50:20
【问题描述】:

如果我有以下接口:

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 值周围是否有更复杂的东西...?

【问题讨论】:

  • 没有时间写一个完整的答案,但我认为你的困惑在于:“我希望它是一个具有构造函数的对象”。它应该是一个对象,它IS 是一个返回HTMLElement 类型的构造函数。

标签: typescript


【解决方案1】:

您收到的第一个错误是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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 2011-02-14
    • 2010-10-29
    • 2011-10-28
    • 1970-01-01
    相关资源
    最近更新 更多