How to work with form elements in typescript
I would like to get form elements through myForm.elements
and then access each element by its name, for example myForm.elements.month
. Typescript doesn't like this b / c, it doesn't know what the form.elements
property contains month
. I thought, let him create an interface! So I did (see code below), but I get this Typescript error:Neither type 'HTMLCollection' nor type 'FormElements' is assignable to the other
Here's the code I'm working with:
interface FormElements {
day: HTMLInputElement;
month: HTMLInputElement;
year: HTMLInputElement;
}
class BirthdateInput {
constructor(form: HTMLFormElement) {
var elements: FormElements = <FormElements> form.elements; // error here
this.day = elements.day;
this.month = elements.month;
this.year = elements.year;
}
}
Any ideas on how best to use my object form.elements
so Typescript won't complain?
source to share
The best way is to write it like this:
// Note 'extends' clause here
interface FormElements extends HTMLFormElement {
day: HTMLInputElement;
month: HTMLInputElement;
year: HTMLInputElement;
}
class BirthdateInput {
constructor(form: HTMLFormElement) {
var elements: FormElements = <FormElements> form.elements; // OK
// ...
source to share
Right or wrong, I found that you can also do something like this:
interface FormElements {
day: HTMLInputElement;
month: HTMLInputElement;
year: HTMLInputElement;
}
class BirthdateInput {
constructor(form: HTMLFormElement) {
var elements: FormElements = <FormElements>(<any> form.elements);
this.day = elements.day;
this.month = elements.month;
this.year = elements.year;
}
}
source to share