javascript - Typescript,'NodeListOf<Element>' is not an array type or a string type - Stack Overfl

Converting my JS to TS strict mode.The following syntax looks fine to me but TS is complaining in the

Converting my JS to TS strict mode.

The following syntax looks fine to me but TS is complaining in the for loop on allSubMenus with:

[ts] Type 'NodeListOf<Element>' is not an array type or a string type.

What am I missing?

function subAct(target:Node){

  const allSubMenus : NodeListOf<Element> = document.querySelectorAll('.subMenuItems') 

  for (const sub of allSubMenus){
    sub.classList.remove('active')
  }  
}

Converting my JS to TS strict mode.

The following syntax looks fine to me but TS is complaining in the for loop on allSubMenus with:

[ts] Type 'NodeListOf<Element>' is not an array type or a string type.

What am I missing?

function subAct(target:Node){

  const allSubMenus : NodeListOf<Element> = document.querySelectorAll('.subMenuItems') 

  for (const sub of allSubMenus){
    sub.classList.remove('active')
  }  
}
Share Improve this question edited Jul 15, 2020 at 8:38 jonrsharpe 122k30 gold badges264 silver badges472 bronze badges asked Aug 7, 2018 at 9:58 SamSam 1,8284 gold badges32 silver badges58 bronze badges
Add a comment  | 

7 Answers 7

Reset to default 44

You need to set the target compiler option to es6 or higher for NodeListOf<T> to be iterable.

According to your typescript target compiler, parsing error can be occured.

The for-of loop, introduced in the sixth edition of EcmaScript (ES6). Thus, old browsers' JS engine can not understand for-of loop syntax. https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/

To solve this issue,

if you support latest modern browsers(>=ES6) only

change your TS target

//tsconfig.json
{
  "compilerOptions": {
    "target": "es6" //above es6 like ES2015,ES2018 ...
  }
}

if you support old browsers(<=ES5)

I presume that you are using next environment.

//.tsconfig.json
{
  "compilerOptions": {
    "target": "es5"
  }
}
  1. To keep for-of loop, use as any syntax

Note: "as any" will cast collection(Objects) to array and this will affect some type features within "for" scope.

//.ts
const allSubMenus : NodeListOf<SpecifiedElement> = document.querySelectorAll('.subMenuItems') 
    
for (const sub of allSubMenus as any){ // then will pass compiler
  sub.classList.remove('active')
}  

The above TS script will be compiled to

//.js output
var allSubMenus = document.querySelectorAll('.subMenuItems');

for (var _a = 0, _b = forms; _a < _b.length; _a++) {
    var sub = _b[_a];
    sub.classList.remove('active');
}

https://stackblitz.com/edit/node-ywn1bq?file=main.js

  1. Use classic for-loop syntax
const allSubMenus : NodeListOf<SpecifiedElement> = document.querySelectorAll('.subMenuItems') 

for (let i = 0; i < allSubMenus.length; i++) { 
  allSubMenus[i].classList.remove('active'); 
}    

<Element>

In addition to the above, to avoid the following warning,

Property '<property name>' does not exist on type 'Element'

you may specify <Element> if you know element type and type define exists.

//for example,
NodeListOf<Element>  => NodeListOf<HTMLFormElement>

ECMAScript(ES) history

https://codeburst.io/javascript-wtf-is-es6-es8-es-2017-ecmascript-dca859e4821c

You could try

const allSubMenus : NodeListOf<Element> = document.querySelectorAll('.subMenuItems') 
Array.from(allSubMenus, subMenu => {/* */})

Set "downlevelIteration": true in compilerOptions in your tsconfig.json file.

From https://www.typescriptlang.org/tsconfig#downlevelIteration

Downleveling is TypeScript’s term for transpiling to an older version of JavaScript. This flag is to enable support for a more accurate implementation of how modern JavaScript iterates through new concepts in older JavaScript runtimes

You can iterate over a NodeListOf with the forEach method.

const allSubMenus : NodeListOf<Element> = document.querySelectorAll('.subMenuItems') 
allSubMenus.forEach(sub => sub.classList.remove('active'))

Source: https://microsoft.github.io/PowerBI-JavaScript/interfaces/_node_modules_typedoc_node_modules_typescript_lib_lib_dom_d_.nodelistof.html#foreach

while compiling your code you may choose target: ES2017 or target: ES2015. also you can set this property in tsconfig.json file unser compilerOptions.

So here is the command line code for that:

npx tsc path/to/file.ts --target ES2015

TIP: if you are using babel along side with typescript, it is totally recommended that you always make typescript to compile to latest version of Javascript, and then let babel handles rest of transpiring process. With this technique you add another lever of assurance of supportive level to older browsers since typescript is not ok to compile the code that would run in for example ie6; so babel comes to rescue here and make you yo make sure that your js code would run in even ie < 9 with it's helpful polyfills and other mechanisms that it takes to work!

So keep in mind that:

Always let typescript compiles your code to latest javascript ( by setting target: ES2017 ) and let babel transpiles your js code to support older browsers ( separate concerns properly and let each one does the related job).

This assumes you want to keep ES5 target (if not, upgrading it to ES6 will solve the issue as well).

  1. Use for loop
function subAct(target:Node){
  const allSubMenus = document.querySelectorAll('.subMenuItems');

  for (let i = 0; i < allSubMenus.length; i += 1){
    const sub = allSubMenus[i];
    sub.classList.remove('active')
  }  
}
  1. Use Array.from

In order to use this, you have to add ES2015.core to compilerOptions.lib and add polyfill for Array.prototype.from Note that this will loop on the collection twice - the first method is better.

function subAct(target:Node){
  const allSubMenus = Array.from(document.querySelectorAll('.subMenuItems'));

  for (const sub of allSubMenus){
    sub.classList.remove('active')
  }  
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1737064134a3920354.html

相关推荐

  • MCP实战

    前言最近热衷于找一些好玩的MCP,集成在cursor中,给大模型外挂许多有趣的功能,例如:什么是MCP?本地如何开发MCP ServerMCP实战 | cursor 如何一句话操作 gitHub 代码库cursor 如何调用 MCP ser

    1小时前
    00
  • win 7系统怎么看计算机配置,windows7系统怎么查看电脑配置

    通常我们在选购电脑的时候都比较注重电脑配置&#xff0c;那么windows7系统怎么查看电脑配置呢?接下来大家跟着学习啦小编一起来了解一下windows7查看电脑配置的解决方法吧。 windows7查看电脑配置方法一&#x

    1小时前
    00
  • 很干!dockerfile最佳实践

    为什么你打包的镜像那么大?为什么打包过程耗时这么久?导致整个部署的效率很低,如果你有这样的疑问,那么很多时候是因为dockerfile的问题,这篇文章将会深入介绍dockerfile的最佳实践,帮助你构建更高效、更小、更可维护的镜像。缓存机

    1小时前
    00
  • Python 爬虫如何伪装 Referer?从随机生成到动态匹配

    一、Referer 的作用与重要性Referer 是 HTTP 请求头中的一个字段,用于标识请求的来源页面。它在网站的正常运行中扮演着重要角色,例如用于统计流量来源、防止恶意链接等。然而,对于爬虫来说,Referer 也可能成为被识别为爬虫

    1小时前
    00
  • 《特斯拉Optimus Gen

    特斯拉推出的Optimus Gen - 2,凭借其多模态感知技术,成为了这场变革中的焦点,为机器人具身智能的发展开辟了全新道路。 想象一下,人类在与世界互动时,并非依赖单一感官,而是通过视觉、听觉、触觉等多种感官协同工作,从而对周围环境形成

    1小时前
    00
  • 完美解决win7系统使用wireshark未响应问题

    Win7系统&#xff0c;安装wireshark4.0的版本&#xff0c;发现打开可以打开&#xff0c;但是只要点击网卡之后就会显示无响应 一开始我以为是位数的原因&#xff0c;之前用的64位的&am

    53分钟前
    00
  • 你的服务器够快吗?一文说清如何衡量服务器的性能?

    本文以一个标准的 Seurat 单细胞分析流程为例,深入探讨衡量计算性能的关键指标——运行时间(Elapsed Time)、CPU 时间(CPU Time)和等待时间(Wait Time)——揭示它们在单线程与多线程环境下的差异及其反映的系

    51分钟前
    00
  • 8.6K star!完全免费+本地运行+无需GPU,这款AI搜索聚合神器绝了!

    嗨,大家好,我是小华同学,关注我们获得“最新、最全、最优质”开源项目和高效工作学习方法 FreeAskInternet是一款革命性的开源项目,它完美结合了多引擎搜索和智能语言模型,让你在不联网、不花钱、不暴露隐私的情况下,获得媲美ChatG

    50分钟前
    00
  • 基于PacBio HiFi数据的人类全基因组重测序变异分析流程

    随着第三代测序技术,特别是PacBio HiFi(High Fidelity)测序技术的发展,我们能够获得兼具长读长和高准确度的测序数据。这为人类全基因组重测序(WGS)分析,尤其是复杂区域和结构性变异(Structural Variati

    48分钟前
    00
  • 瞧瞧别人家的日期处理,那叫一个优雅!

    前言在我们的日常工作中,需要经常处理各种格式,各种类似的的日期或者时间。比如:2025-04-21、20250421、2025年04月21日等等。有些字段是String类型,有些是Date类型,有些是Long类型。如果不同的数据类型,经

    46分钟前
    00
  • 飞书多维表格批量转换

    之前一直以为,飞书多维表格是专门用来协作的,除了漂亮一点也没啥。近期偶然得知飞书多维表格已经新增了 AI 的加持,变得不得了了,今天就来分享一个场景:不同数据库 SQL 格式的批量转换。假设你现在有一批 Oracle 脚本,现在因为某种原因

    38分钟前
    00
  • KB2533623补丁安装指南 - 解决Win7下无法运行.NET 67 WinForm应用

    KB2533623补丁安装指南 - 解决Win7下无法运行.NET 67 WinForm应用 项目地址:https:gitcodeopen-source-toolkit62304 概览 对于所有遇到Windows 7系统无法

    35分钟前
    00
  • Fabric8 Kubernetes 日志工具实践

    最近在使用 Fabric8 Kubernetes Client 的过程中发现了新大陆一样,感觉利用这个库可以进行很多有趣的功能尝试,其中一个便是日志的本地化。原因无他,rancher 页面性能实在太差了,经常性的暂停工作,碰到故障排查的时候

    34分钟前
    00
  • Sentinel 的熔断和限流

    在分布式系统里,服务之间牵一发而动全身,一个接口雪崩,可能带崩整个应用链路。要想系统抗住流量洪峰,顶住突发异常,就得在稳定性上下功夫。今天我就来说说稳定性保障里的老将——Sentinel,看看它是怎么凭借限流熔断,在服务治理的江湖里占得一席

    33分钟前
    00
  • OceanBase 单机版可以大批量快速部署吗? YES

    OceanBase的单机版已经开放给一些老师测试了,有幸被邀请进行单机测试,这次可以测试的是商业版,我已经好久没有尝试一个商业版线下的数据库试用了,上一次还是SQL SERVER 2019 的180天版本。测试企业OB版本测试企业OB版本目

    29分钟前
    00
  • windows7计算机图片,win7照片查看器无法显示图片计算机可用内存不足 需要技巧...

    很多人在使用win7图片查看器的时候&#xff0c;查看图片都有遇到内存不足的情况&#xff0c;却又不知道是什么原因&#xff0c;该怎么处理&#xff0c;那么今天我们就一起来看看吧。 工具材料 ●电脑

    27分钟前
    20
  • Oracle中删除的列数据可以进行恢复么?

    有朋友提出闪回可以恢复删除的列(包括数据),这个可行么?实践是检验真理的唯一标准,创建一张测试表,代码语言:javascript代码运行次数:0运行复制CREATE TABLE t_flash_01 (id NUMBER, c1 varch

    26分钟前
    20
  • AI 英语能力评估App的开发

    开发一款 AI 英语能力评估 App 是一个系统工程,它结合了移动应用开发、后端服务构建、人工智能模型研发和教育评估理论。整个过程比开发一个普通 App 要复杂得多,需要多领域的技术和专业知识。以下是开发这样一个 App 的关键环节。1.

    23分钟前
    20
  • goframe这个劲爆的脚手架做项目还是非常不错

    goframe一个由国人封装的go语言框架,模块化的设计理念非常不错。要学习goframe框架内的相关技术,找一个成熟的系统进行研读是入门提高的不错选择。今天分享一个基于goframe框架的开发的后台管理系统。功能非常不错,而且前后端代码都

    19分钟前
    00
  • OFC 2025 TeraHop报告:AI数据中心光连接技术

    在人工智能技术快速发展的背景下,AI数据中心的建设对光模块技术提出了更高要求。TeraHop在OFC 2025会议上的报告,深入探讨了这一领域的现状与未来。一、AI数据中心光互连面临的挑战(一)传输速率升级加速过去光

    14分钟前
    00

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信