Skip to content

Built-in Symbol.iterator methods return IterableIterator<T> extending Iterator<T>, not Iterator<T, undefined> #52998

Closed
@lionel-rowe

Description

@lionel-rowe

lib Update Request

The built-in Symbol.iterator methods return IterableIterator<T> extending Iterator<T>, not the expected Iterator<T, undefined>. For example:

const char = string[Symbol.iterator]().next().value

The expected type of char is string | undefined, but instead it's any. This isn't correct — it will never be anything other than a string (strictly a single Unicode char) or undefined at runtime.

This looks to be related to #33353, which was closed due to backwards-compatibility concerns; however, it could presumably fixed without changing the default types of IterableIterator, instead changing its definition to take an extra type parameter:

- interface IterableIterator<T> extends Iterator<T> {
-     [Symbol.iterator](): IterableIterator<T>;
+ interface IterableIterator<T, TReturn = any> extends Iterator<T, TReturn> {
+     [Symbol.iterator](): IterableIterator<T, TReturn>;
  }

And then changing all the built-ins (String, Array, etc) like so:

  interface String {
      /** Iterator */
-     [Symbol.iterator](): IterableIterator<string>;
+     [Symbol.iterator](): IterableIterator<string, undefined>;
  }

Could that work as a fix and be sufficiently backward-compatible?

Configuration Check

My compilation target is ES2020 and my lib is the default.

Missing / Incorrect Definition

Various — any built-in JS type with a Symbol.iterator method, such as Array, String, Map, Set, Uint8Array, etc.

Sample Code

const char = string[Symbol.iterator]().next().value
// expected type: string | undefined
// actual type: any

const definitelyChar = nonEmptyString[Symbol.iterator]().next().value!
// expected type: string
// actual type: any

Documentation Link

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/@@iterator

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions