Search code examples
typescriptgeneratoriterable

How to make TypeScript not complain about Iterator.prototype.take()?


I want to use Iterator.prototype.take() in my code but TypeScript keeps complaining it doesn't exist even though in runtime everything works as expected.

Property 'take' does not exist on type 'Generator<number, void, unknown>'

Here is the full code (playground link):

function* rangeFrom<T>(arr: T[]) {
  let count = 0
  let i = 0

  while (true) {
    const value = arr[i]!
    yield value;

    count += 1
    i = i === arr.length - 1 ? 0 : i + 1
  }
}

const iterable = rangeFrom([1, 2, 3, 4, 5])
console.log(...iterable.take(8))

I couldn't find anything about generator functions in TypeScript. Also tried adding every possible ESNext feature to compilerOptions.lib array in tsconfig.json but that didn't help.

I feel like i am missing something super obvious but can't figure out what exactly.


Solution

  • The problem was the version of TypeScript i was using which was 5.5.4. After upgrading to 5.6.3 the problem went away. TypeScript 5.6 announcement blog post mentions adding support for iterator helper methods here.