我正在使用以下代码将 DOM 节点列表转换为数组:
const elements = [...document.getElementsByClassName(selector)];
但是使用 TypeScript 我会收到如下错误:Type 'HTMLCollectionOf<Element>' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator.
我不确定在这种情况下我应该怎么做。我试着这样输入:
const elements: HTMLElement[] = [...document.getElementsByClassName(selector)];
但它不起作用。
这是我的 TypeScript 配置文件 ( tsconfig.json
):
{
"compilerOptions": {
"target": "es5",
"module": "umd",
"sourceMap": true,
"outDir": "dist",
"strict": true,
"esModuleInterop": true,
"downlevelIteration": true
}
}
最佳答案
问题是默认情况下 Typescript 将默认使用 .slice。
您应该添加标志 --downlevelIteration 以使其适用于所有迭代器,包括 html 集合。
https://www.typescriptlang.org/docs/handbook/compiler-options.html
您应该将 dom.iterable 作为一个库才能工作。您目前没有指定 lib,因此根据您的目标使用默认值,这就是它不起作用的原因。
关于javascript - 传播 getElementsByClassName 或 querySelectorAll 会在 TypeScript 中产生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57230148/