我使用以下代码将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
}
}
发布于 2019-07-27 15:50:20
问题是,默认情况下,Typescript将默认使用.slice。
您应该添加标志--downlevelIteration,以使其适用于所有迭代器,包括html集合。
https://www.typescriptlang.org/docs/handbook/compiler-options.html
您应该将dom.iterable作为库才能使其工作。您当前没有指定lib,因此根据您的目标使用默认值,这就是它不起作用的原因。
https://stackoverflow.com/questions/57230148
复制相似问题