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?

+3


source to share


3 answers


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
        // ...

      

+4


source


It turns out adding the sentence extends

fixes it:



interface FormElements extends HTMLCollection {
    day: HTMLInputElement;
    month: HTMLInputElement;
    year: HTMLInputElement;
}

      

+2


source


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

      

0


source







All Articles