3

尝试解构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不会发出此错误的类型注释。

4

1 回答 1

1

This is a limitation of the standard DOM definitions library (and still is in 2021). Here is how the HTMLFormControlsCollection is defined in it - notice the lack of a string index signature (this is exactly why the error happens):

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;
}

Its parent interface HTMLCollectionBase also lacks a string index signature (despite having a number index signature):

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;
}

However, HTMLFormControlsCollection should have a string index signature by definition (see the standard):

element = collection[name]
radioNodeList = collection[name]
Returns the item with ID or name name from the collection.

So, with the help of some declaration merging, we can fix the omission:

interface HTMLFormControlsCollection extends HTMLCollectionBase {
  [item: string]: Element | RadioNodeList;
}
于 2021-05-23T16:58:26.000 回答