无法获得for..of循环工作在打字稿

时间:2018-05-11 07:14:46

标签: typescript ecmascript-6

我正在尝试使用TypeScript在VS Code中创建自定义迭代。它不会通过它迭代。我究竟做错了什么?我已将目标设置为es6并尝试使用和不使用下层生成标记。

// this works
test("can iterate array", () => {
    let total = 0;
    for (let i of [1, 2, 3]) {
        total = total + i;
    }
    expect(total).toBe(6);
});

function* numbers() {
    yield 1;
    yield 2;
    yield 3;
}

let myInterable = {
    [Symbol.iterator]: numbers
};

// this does NOT work
test("can iterate custom", () => {
    let total = 0;
    for (let i of myInterable) {
        total = total + i;
    }
    expect(total).toBe(6);
});

这是我的tsconfig.json ...

的相关部分
"compilerOptions": {
  "module": "esnext",
  "target": "es6",
  "lib": [
    "es6",
    "dom"
  ],
  "sourceMap": true,
  "allowJs": true,
  "jsx": "react",
  "moduleResolution": "node",
  "rootDir": "src",
  "forceConsistentCasingInFileNames": true,
  "noImplicitReturns": true,
  "noImplicitThis": true,
  "noImplicitAny": true,
  "strictNullChecks": true,
  "suppressImplicitAnyIndexErrors": true,
  "noUnusedLocals": false

1 个答案:

答案 0 :(得分:0)

我不得不重启VS Code。以下所有测试都通过了。

test("can iterate array", () => {
    let total = 0;
    for (let i of [1, 2, 3]) {
        total = total + i;
    }
    expect(total).toBe(6);
});

function* numbers() {
    yield 1;
    yield 2;
    yield 3;
}

test("can iterate custom", () => {
    let total = 0;
    for (let i of numbers()) {
        total = total + i;
    }
    expect(total).toBe(6);
});

test("can iterate custom iterable", () => {
    let x = {
        [Symbol.iterator]: numbers
    };
    let total = 0;
    for (let i of x) {
        total = total + i;
    }
    expect(total).toBe(6);
});

在package.json中......

" target":" es6",     " lib":[       " ES6&#34 ;,       " DOM"     ],