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?
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.
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:
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.
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.
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
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With