The following error appears when trying to destructure a form.elements
object:
Type 'HTMLFormControlsCollection' has no property 'x' and no string index signature
// 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
}
I don't want to use the : any
type annotation that does not emit this error.
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):Its parent interface
HTMLCollectionBase
also lacks a string index signature (despite having a number index signature):However,
HTMLFormControlsCollection
should have a string index signature by definition (see the standard):So, with the help of some declaration merging, we can fix the omission: