ウェブサイト検索

javascript - Typescript、'NodeListOf' は配列型でも文字列型でもありません


私のJSをTSの厳密モードに変換すること。

次の構文は私には問題ないように見えますが、TSはallSubMenusのforループで次のように文句を言っています:

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

何が足りないのですか?

function subAct(target:Node){

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

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

回答 #1

NodeListOf<T> を反復可能にするには、target コンパイラオプションを es6 以上に設定する必要があります。

回答 #2

あなたのTypeScriptターゲットコンパイラーによると、解析エラーが発生する可能性があります。

EcmaScriptの第6版(ES6)で導入されたfor-ofループ。したがって、古いブラウザのJSエンジンはfor-ofループの構文を理解できません。https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/

この問題を解決するために、

最新のモダンブラウザ(>=ES6)のみをサポートする場合

TSターゲットを変更する

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

もし古いブラウザ(<=ES5)をサポートする場合

あなたは次の環境を使用していると推測します。

//.tsconfig.json
{
  "compilerOptions": {
    "target": "es5"
  }
}
  1. for-ofループを維持するには、as any構文を使用してください

注: 「as any」はコレクション(オブジェクト)を配列にキャストし、これにより「for」スコープ内のいくつかの型機能に影響を与えます。

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

上記のTSスクリプトは次のものにコンパイルされます

//.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. 古典的な for ループ構文を使用する
const allSubMenus : NodeListOf<SpecifiedElement> = document.querySelectorAll('.subMenuItems') 

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

<元素>

上記に加えて、次の警告を避けるために、

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

要素の種類と型定義が存在する場合、<Element>を指定することができます。

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

ECMAScript(ES) の歴史

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

関連記事