【问题标题】:Type 'HTMLFormControlsCollection' has no property 'x' and no string index signature类型“HTMLFormControlsCollection”没有属性“x”并且没有字符串索引签名
【发布时间】:2018-09-11 15:18:20
【问题描述】:

尝试解构form.elements 对象时出现以下错误:

类型“HTMLFormControlsCollection”没有属性“x”,也没有字符串索引签名

// in a class

domRefs: {[key: string]: HTMLFormElement | null} = {
  myForm: null
}

onButtonClick = () => {
  console.debug(this.domRefs.myForm!.elements) // screenshot below
  const {a, b, c} = this.domRefs.myForm!.elements
}

我不想使用不会发出此错误的: any 类型注释。

【问题讨论】:

  • 我相信你很久以前就已经解决了 - 但只是为了其他读者的利益 - 像往常一样,罪魁祸首是标准定义库的限制,除了扩充之外别无他法HTMLFormControlsCollection 接口。

标签: typescript index-signature typescript-lib-dom


【解决方案1】:

这是标准 DOM 定义库的限制(在 2021 年仍然存在)。以下是 HTMLFormControlsCollection 在其中的定义方式 - 请注意缺少字符串索引签名(这正是发生错误的原因):

interface HTMLFormControlsCollection extends HTMLCollectionBase {
    /**
     * Returns the item with ID or name name from the collection.
     * 
     * If there are multiple matching items, then a RadioNodeList object containing all those elements is returned.
     */
    namedItem(name: string): RadioNodeList | Element | null;
}

它的父接口HTMLCollectionBase也缺少字符串索引签名(尽管有数字索引签名):

interface HTMLCollectionBase {
    /**
     * Sets or retrieves the number of objects in a collection.
     */
    readonly length: number;
    /**
     * Retrieves an object from various collections.
     */
    item(index: number): Element | null;
    [index: number]: Element;
}

但是,HTMLFormControlsCollection 根据定义应该有一个字符串索引签名(参见the standard):

元素 = 集合[名称]
radioNodeList = 集合[名称]
从集合中返回具有 ID 或名称 name 的项目。

所以,在一些声明合并的帮助下,我们可以修复遗漏:

interface HTMLFormControlsCollection extends HTMLCollectionBase {
  [item: string]: Element | RadioNodeList;
}

【讨论】:

    猜你喜欢
    • 2018-03-27
    • 2018-12-15
    • 2015-02-02
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2020-07-09
    相关资源
    最近更新 更多