网站搜索

typescript - 为什么在 ES6 目标下 Array.fill() 不可用


我正在将一些 js 代码迁移到 typescript,并且在使用 Array.fill 时遇到了一些问题。

我曾经有过这段代码

Array(4).fill(0).map()

我把它改成了

Array<number>(4).fill(0).map()

但是我收到了这个错误

Error:(22, 49) TS2339:Property 'fill' does not exist on type 'number[]'.

我的 tsconfig.json 看起来像

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "removeComments": false,
    "outDir": "dist",
    "allowJs": true
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.js"
  ],
  "exclude": [
    "node_modules",
    "dist",
    "src/**/*.spec.ts",
    "src/**/*.spec.js"
  ]
}

我已经检查了这个问题 #9436。

我错过什么了吗?

答案#1

试试这个:

let arr:Array<Number>=new Array(8);
arr.fill(0);

希望这能帮到你 :)