Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

※前提: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>;
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away