2015-04-27 49 views
3

我想通過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; 
    } 
} 

任何想法就如何更好地施展我的form.elements對象所以打字稿不會抱怨?

回答

4

最好的辦法是把它寫這樣的:

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

'FormElements'實際上對應於form.elements,而不是表單本身,所以它更好從'HTMLCollection'擴展,或者可能'HTMLFormControlsCollection'擴展爲'HTMLFormElement'。但「擴展」方面是正確的。 – lizlux

2

原來添加extends條款修正它:

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

無論是對還是錯,我發現,你也可以做像這樣:

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