输入' HTMLFormControlsCollection'没有财产' x'并且没有字符串索引签名

时间:2018-04-02 11:48:52

标签: typescript

尝试对import cv2对象进行解构时会出现此错误。

form.elements

enter image description here

我不想使用不会发出此错误的// 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 } 类型。

1 个答案:

答案 0 :(得分: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;
}
相关问题