LoginSignup
0
0

More than 5 years have passed since last update.

ユーザー定義でIteratorを作成しようとするとエラーが出力される。

Posted at

※前提:strictNullCheckが有効、targetがes2015以上

下記のコードをコンパイルしようとするとエラーが発生します。

class MyIterableIterator implements IterableIterator<number> {
  __count = 0;
  [Symbol.iterator]() {
    return this;
  }
  next() {
    const count = this._count;
    if (count < 10) {
      this.count++;
      return { value: count, done: false };
    }

    // ↓この一行でエラーが発生する
    return { done: true };
  }
}

javascriptのIterator Protocolでは、iterator.next()が返すオブジェクトはdoneプロパティがtrueのとき、valueプロパティを省略してよい、と定められております。

しかし、現在のTypeScript(3.0)ではvalueプロパティを省略することができませんし、undefinedを代入することもできません。

この問題はすでに公式issueに報告されていますが、DefinitelyTypedライブラリと競合するため、修正できないのが現状です。
https://github.com/Microsoft/TypeScript/issues/11375

現在の回避策としては、asキャストや型アサーション演算子で凌ぐしかありません。

return { done: true } as IteratorResult<number>;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0