ค้นหาเว็บไซต์

typescript - ประเภท 'IterableIterator' ไม่ใช่ประเภทอาเรย์หรือประเภทสตริง


ฉันได้รับข้อผิดพลาดดังต่อไปนี้เมื่อพยายามสร้างช่วงของตัวเลขแบบไดนามิก

Type 'IterableIterator<number>' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.

ฉันพบคำถามที่มีอยู่แล้ว แต่แนวทางแก้ปัญหาไม่ได้ผลสำหรับฉัน

TypeScript และ Iterator: ประเภท 'IterableIterator' ไม่ใช่ประเภทอาเรย์

การตั้งค่าของฉันมีดังนี้...

  • ฉันใช้คำสั่ง 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: es6 และ downlevelIteration: 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"]
}

คำตอบ #1

ดูเหมือนว่ามันเข้มงวดและไม่ต้องการสร้างอาร์เรย์โดยใช้ spread จาก iterator (ซึ่งไม่ใช่อาร์เรย์) อย่างไรก็ตามสามารถสร้างอาร์เรย์จาก iterator โดยใช้ฟังก์ชัน Array.from ได้:

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

Array.from รับ Iterable.

บทความที่เกี่ยวข้อง