在 Typescript 中,如何使用扩展语法为 querySelectorAll 设置类型

Posted

技术标签:

【中文标题】在 Typescript 中,如何使用扩展语法为 querySelectorAll 设置类型【英文标题】:In Typescript how can I set types for querySelectorAll with the spread syntax 【发布时间】:2019-02-11 04:36:25 【问题描述】:

我有这个代码。

const elements = [...document.querySelectorAll('.someClass')]

组合:

querySelectorAll 扩展运算符

我不知道如何将 Typescript 类型添加到这一行。

我从控制台收到错误:

TS2548: Type 'NodeListOf<Element>' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator.

【问题讨论】:

【参考方案1】:

当你定位 es5 时它不起作用,因为 TypeScript 不支持 Symbol.iterator 的填充/polyfiling

如果您以es6 为目标,它将起作用。

或者,您可以使用Array.from 使用lib 选项:

const elements = [...Array.from(document.querySelectorAll('.someClass'))]

或者更简单地说:

const elements = Array.from(document.querySelectorAll('.someClass'))

【讨论】:

非常感谢,我会试试Array.from() 的建议。我认为 Babel 的转换是不完美的并且 Typescript 在原则上坚持真正的转换是正确的吗?因此,没有办法像 Babel 那样选择转换扩展运算符。我是 Typescript 的初学者,有没有推荐的“Type Up”Array.from() 版本的方法?

以上是关于在 Typescript 中,如何使用扩展语法为 querySelectorAll 设置类型的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Typescript 在 React 中扩展 HTML 属性

如何将 typescript npm 模块导入语法转换为 ECMA2015 模块导入语法

我可以使用扩展语法使用 TypeScript 制作包装函数,而无需指定参数和类型吗?

TypeScript语法学习

TypeScript语法学习

TypeScript语法学习