【问题标题】:Type 'IterableIterator<number>' is not an array type or a string type类型 'IterableIterator<number>' 不是数组类型或字符串类型
【发布时间】:2022-01-13 17:22:47
【问题描述】:

尝试生成动态数字范围时出现以下错误。

Type 'IterableIterator&lt;number&gt;' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.

我发现了一个现有问题,但该解决方案对我不起作用。

TypeScript and Iterator: Type 'IterableIterator<T>' is not an array type

我的设置如下...

  • 我使用了命令npx create-next-app@latest --ts
class FlexGrid extends React.Component {

    range(size: number, startAt = 0) {
        return [...Array(size).keys()].map(i => i + startAt);
    }

我尝试设置target: es6downlevelIteration: true 都不能解决错误。

{
  "compilerOptions": {
    "target": "es6",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "downlevelIteration": true
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}

【问题讨论】:

  • 如果我在一个文件夹中使用tsc -p . 构建该代码,该文件夹包含一个包含您的代码的文件和一个包含您发布的配置的 tsconfig,我不会收到任何错误。你确定 tsconfig 正在被提取吗?
  • 你在哪里看到这个错误?您发布的代码在 typescript playground 上没有报告任何错误。
  • @Titan -- 不,我不确定......但是因为我只是使用了命令npx create-next-app@latest --ts,并且项目中的所有内容都是自动生成的,所以我不知道会是什么情况跨度>
  • @tromgy -- 我在运行npm run build 时看到这个错误,它映射到命令next build

标签: typescript ecmascript-6 next.js


【解决方案1】:

显然它是严格的,并且不想使用迭代器(不是数组)的传播来创建数组。但是,可以使用 Array.from 函数从迭代器创建数组:

range(size: number, startAt = 0) {
  return Array.from(Array(size).keys()).map((i) => i + startAt);
}

Array.from 接受Iterable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-19
    • 2019-11-21
    • 2022-11-28
    • 1970-01-01
    • 2022-01-02
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多