簡體   English   中英

TS 7015:元素隱式具有“任何”類型,因為索引表達式不是 Object 的“數字”類型。getElementsByTagName 的鍵

[英]TS 7015: Element implicitly has an 'any' type because index expression is not of type 'number' for Object.keys of getElementsByTagName

我有這個 typescript 錯誤Element implicitly has an 'any' type because index expression is not of type 'number' when trying to type key from Object.keys of getElementsByTagName('button').

這是我的代碼:

const buttonElements: HTMLCollectionOf<HTMLButtonElement> = blockRef.current.getElementsByTagName(
  'button',
);
if (buttonElements) {
  Object.keys(buttonElements).forEach((key: string) => {
    buttonElements[key].addEventListener('click', handleOpenModal, false);
  });
}

在這里,我在forEach()中使用了 type key: string並且我在buttonElements[key]中遇到了類型錯誤。 我發現了其他人遇到的類似問題,並發現使用索引簽名是解決方案,但是我不確定如何添加索引簽名或擴展 object,因為這個 object 是HTMLCollectionOf<HTMLButtonElement>類型。

我試過的方法:

  • buttonElements[key as keyof HTMLCollectionOf<HTMLButtonElement>]
  • buttonElements[key as string]
  • const buttonElements: HTMLCollectionOf<string, HTMLButtonElement> = blockRef.current.getElementsByTagName('button',);

非常感謝任何幫助正確鍵入key或更好地鍵入buttonElements的幫助。 謝謝你們!

這是因為Object.keys()返回一個鍵數組,但HTMLCollectionOf<>實際上包含一個 object,其中數字用作索引。 這意味着在使用它訪問buttonElement集合中的任何條目之前,您需要手動將key轉換為數字(例如,通過使用一元運算符++key ):

Object.keys(buttonElements).forEach((key) => {
  buttonElements[+key].addEventListener('click', handleOpenModal, false);
});

此外,我實際上建議不要使用getElementsByTagName ,因為querySelectorAll是一種更現代的方法並且實際上是可迭代的,並且您可以使用for...of遍歷節點列表:

const buttonElements = blockRef.current.querySelectorAll('button');
for (const buttonElement of buttonElements) {
  buttonElement.addEventListener('click', handleOpenModal, false);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM