类型“ ChildNode”缺少类型“ HTMLOptionElement”中的以下属性

时间:2019-11-15 23:42:26

标签: typescript

这是我的方法:

public deleteSelectOption( index: number ): void {
  this.elements.lyricsLineSelect.forEach( ( el: HTMLSelectElement )  => {
    el.childNodes[ index ].remove();
    el.childNodes.forEach( ( option: HTMLOptionElement, i: number ) => {
      if( i >= index ){
        option.value = i.toString();
        option.textContent =  `${ i + 1 }. ${ this.lyrics[ i ].text }`;
      }
    } );
  } );
}

尝试使用forEach循环遍历el.childNode时遇到此错误:

Argument of type '(option: HTMLOptionElement, i: number) => void' is not assignable to parameter of type '(value: ChildNode, key: number, parent: NodeListOf<ChildNode>) => void'.
Types of parameters 'option' and 'value' are incompatible.
Type 'ChildNode' is missing the following properties from type 'HTMLOptionElement': defaultSelected, disabled, form, index, and 190 more.ts(2345)

如何让打字稿知道el.childNodesHTMLOptionElement的数组?

1 个答案:

答案 0 :(得分:0)

解决方案是替换此行

el.childNodes.forEach( ( option: HTMLOptionElement, i: number ) => {

对此

( el.childNodes as NodeListOf<HTMLOptionElement> ).forEach( ( option: HTMLOptionElement, i: number ) => {