【问题标题】:Spreading getElementsByClassName or querySelectorAll gives an error in TypeScript传播 getElementsByClassName 或 querySelectorAll 会导致 TypeScript 出错
【发布时间】: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


【解决方案1】:

问题是默认情况下 Typescript 会默认使用 .slice。

您应该添加标志 --downlevelIteration 使其适用于所有迭代器,包括 html 集合。

https://www.typescriptlang.org/docs/handbook/compiler-options.html

您应该将 dom.iterable 作为一个库来运行。您当前没有指定 lib,因此根据您的目标使用默认值,这就是它不起作用的原因。

【讨论】:

  • 请查看问题的更新描述。我已经添加了我的配置。如您所见,该标志设置为 true。
  • 我编辑了我的答案,如果您添加正确的库,它应该可以工作
猜你喜欢
  • 2018-08-24
  • 1970-01-01
  • 2020-10-04
  • 2023-01-12
  • 2014-06-20
  • 1970-01-01
  • 2012-11-14
  • 2013-12-27
  • 1970-01-01
相关资源
最近更新 更多