Typescript: Make iterable interfaces by extending instead of method defining

Created on 5 Nov 2017  路  5Comments  路  Source: microsoft/TypeScript

[Symbol.iterator](): IterableIterator<T>; is verbose. It is not modern es style. Should use extends Iterable<T> instead.

TypeScript Version: master

Expected behavior:

interface NonIterableIterator<T> {
    next(value?: any): IteratorResult<T>;
    return?(value?: any): IteratorResult<T>;
    throw?(e?: any): IteratorResult<T>;
}

interface Iterator<T> extends NonIterableIterator<T> {
    [Symbol.iterator](): Iterator<T>;
}

interface Iterable<T> {
    [Symbol.iterator](): Iterator<T>;
}

interface Array<T> extends Iterable<T> {
}

or

interface Iterable<T, I extends NonIterableIterator<T> = Iterator<T>> {
    [Symbol.iterator](): I;
}

Actual behavior:

interface Iterator<T> {
    next(value?: any): IteratorResult<T>;
    return?(value?: any): IteratorResult<T>;
    throw?(e?: any): IteratorResult<T>;
}

interface Iterable<T> {
    [Symbol.iterator](): Iterator<T>;
}

interface IterableIterator<T> extends Iterator<T> {
    [Symbol.iterator](): IterableIterator<T>;
}

interface Array<T> {
    /** Iterator */
    [Symbol.iterator](): IterableIterator<T>;
}
Bug lib.d.ts good first issue help wanted

Most helpful comment

Seems like a good idea. PRs are welcome.

All 5 comments

Seems like a good idea. PRs are welcome.

I would like to work on this issue but i need some help for my first PR

I think @falsandtru already has a PR out.

An Iterable subtype should be able to define its own return type for [Symbol.iterator]() as long as it is assignment compatible. Adding an extra type parameter to Iterable for this case seems unnecessary and uses up a type argument position better reserved for possibly defining the TReturn and TNext types, as per #30790. It also will result in significantly more verbose output when we emit declaration files and infer an Iterable<T, I>, since we always emit all type arguments for inferred types.

To be clear, the problem caused by this issue will be fixed by #30790.

Was this page helpful?
0 / 5 - 0 ratings