如何使用打字稿中的表单元素

liz*_*lux 5 javascript casting typescript

我想通过访问表单元素myForm.elements,然后按其名称访问每个元素,例如myForm.elements.month。Typescript不喜欢这个b / c,也不知道它form.elements包含的属性month。我想,让我们创建一个界面!因此,我做到了(请参见下面的代码),但是出现此打字稿错误:Neither type 'HTMLCollection' nor type 'FormElements' is assignable to the other

这是我正在使用的代码:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

关于如何更好地投射form.elements对象以便打字稿不会抱怨的任何想法?

Rya*_*ugh 6

最好的方法是这样写:

// 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
        // ...
Run Code Online (Sandbox Code Playgroud)

  • `FormElements` 实际上对应于 form.elements,而不是表单本身,所以最好从 `HTMLCollection` 或可能的 `HTMLFormControlsCollection` 扩展而不是 `HTMLFormElement`。但是“扩展”方面是正确的。 (3认同)

liz*_*lux 5

原来添加一个extends子句可以修复它:

interface FormElements extends HTMLCollection {
    day: HTMLInputElement;
    month: HTMLInputElement;
    year: HTMLInputElement;
}
Run Code Online (Sandbox Code Playgroud)