Why forEach does not exist on NodeListOf

前端 未结 2 1342
梦如初夏
梦如初夏 2021-01-11 14:01

My code:

    var checkboxes = this.element.querySelectorAll(\"input[type=checkbox]\") as NodeListOf;
    checkboxes.forEach(ele =>         


        
2条回答
  •  鱼传尺愫
    2021-01-11 14:18

    Honestly you could convert a NodeListOf to an array so that typescript will not complain about nodelist.forEach, but this is only solving the problem by adding unnecessary code. You can tell typescript to understand the native nodelist.forEach syntax by adding the dom.iterable library to your tsconfig.json. Here is an example of one of my tsconfig.json files.

    {
      "compilerOptions": {
      "outDir": "./public/js/",
      "noImplicitAny": true,
      "module": "es6",
      "target": "es5",
      "allowJs": true,
      "moduleResolution": "node",
      "rootDir": "src",
      "lib": [
        "es6",
        "dom",
        "dom.iterable"
      ],
      "typeRoots": [
        "node_modules/@types"
      ],
      "removeComments": false
      },
      "include": [
        "src/**/*.ts"
      ],
      "exclude": [
        "node_modules",
        "public",
        "**/*.spec.ts"
      ]
    }
    

    Not all browsers support nodelist.forEach so I would definitely polyfill it https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach

提交回复
热议问题