Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with form elements in typescript

I'd like to access form elements via myForm.elements, and then access each element by it's name, for example, myForm.elements.month. Typescript doesn't like this b/c it doesn't know that form.elements contains a property of month. I thought, let's create an interface! So I did, (see code below), but I'm getting 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 to better cast my form.elements object so typescript won't complain?

like image 512
lizlux Avatar asked Apr 27 '15 22:04

lizlux


People also ask

How do I use Java data types in typescript?

When creating forms, you can use the data types you already have in Java. There is no need to define the same types again in order to use them in TypeScript. Vaadin automatically generates TypeScript types for data entities and form models, based on the Java data model.

How can I write (let entry of data) in typescript?

Now you can for (let entry of data.entries ()) to your heart's content! That's still not as concise as it could be, though - in JavaScript you can just write (let entry of data). We can allow this pattern in TypeScript by adding one more line to tsconfig.json:

Why can't I use for of in typescript?

Using for..of causes TypeScript to complain that data is not an iterator (I think it is, or at least in JS it can be used like one with for...of ), or that data has no such property entries. This makes a little more sense - it doesn't yet in all environments.

How do I query for a form in HTML form element?

We used the querySelector method to query for the form with the myform ID. The HTMLFormElement interface represents a <form> element in the DOM. It allows access to—and, in some cases, modification of—aspects of the form, as well as access to its component elements.


1 Answers

Best way would be 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
        // ...
like image 74
Ryan Cavanaugh Avatar answered Oct 21 '22 05:10

Ryan Cavanaugh