我想通过 myForm.elements
访问表单元素,然后通过名称访问每个元素,例如 myForm.elements.month
。 Typescript 不喜欢这个 b/c 它不知道 form.elements
包含 month
的属性。我想,让我们创建一个界面吧!所以我做了,(见下面的代码),但我收到了这个 typescript 错误: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;
}
}
关于如何更好地转换我的 form.elements
对象以便 typescript 不会提示的任何想法?
最佳答案
最好的方法是这样写:
// 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
// ...
关于javascript - 如何在 typescript 中使用表单元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29907163/