【发布时间】:2019-07-27 07:39:44
【问题描述】:
我正在使用以下代码将 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
}
}
【问题讨论】:
-
在 TS 3.5.2 上为我工作(我在
lib.dom.iterable.d.ts中看到了迭代器定义),现代浏览器中的 HTMLCollections 确实有迭代器 -
我正在使用 TypeScript 3.5.2,它在大喊大叫。可能是配置问题?
标签: javascript arrays typescript spread