Open akdor1154 opened 7 years ago
Is this extremely common? Seems like a potential footgun.
I only really dabble in frontend, but I hit it when trying to use the subclass HTMLFormControlsCollection, where it makes a lot of sense from a user perspective (form.elements['username'], form.elements['password']).
Is this extremely common? Seems like a potential footgun.
Seems you could be talking about JS itself :p
To add to the discussion, the presence of a string index on the interface is defined by the DOM standard (as a named property getter). Since the interface is still widely used (as methods getElementsByClassName
and getElementsByTagName
return HTMLCollection
s of elements), it would make sense to support string indexing.
Also, being able to access elements by id/name allows for the use of destructuring assignment with objects:
interface HTMLCollectionOf<T extends Element> {
[id:string]: T | undefined
}
const { forms: { form1, form2 } } = document;
as well as use computed property names to access form inputs. A bit contrived example to illustrate the use case:
//HTMLCollectionOf same as above
const myFormPrefix = "wpforms-form";
const formIds = [330, 340, 350];
const { forms } = document;
const wpfs = formIds.map((id) => forms[`${myFormPrefix}-${id}`]);
Not sure how common this is (likely not much since this is open for years with little activity), but I just ran into this when migrating some legacy codebase in the form of:
function getFormElement(form: HTMLFormElement, elementName: string) {
return form.elements[elementName]; // Element implicitly has an 'any' type because index expression is not of type 'number'.
}
It should be handled the same way as HTMLFormElement
.
Accessing it via something like document.forms.formName
is a common usage pattern.
According to MDN, HTMLCollection should be string indexable:
TypeScript Version: master
Code