Home > Mobile >  How to traverse a recursive generator in TypeScript?
How to traverse a recursive generator in TypeScript?

Time:10-14

So I have this generator which simply gets subsets from a given array.

export class GenerateThings {
    static *generateSubsets(elements: any[], offset: number = 0) {
        while (offset < elements.length) {
            const first = elements[offset];
            for (const subset of this.generateSubsets(elements, offset   1)) {
                subset.push(first);
                yield subset;
            }
        }
        yield [];
    }
}

This works in plain javascript (without types, of course) but when I build it on TypeScript like this, it says

'generateSubsets' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.

Is there a way to traverse the resulting subset of a set if we use this recursive approach in TypeScript? Thanks.

CodePudding user response:

As @DemiPixel mentioned in the comments above, you can use the Generator type as the explicit return type for your function, such as Generator<any[], void, void> which means the generator yields an array of any, returns nothing, and expects nothing to be passed when next() is called.

However, even better in this case would be to take things to the next level and use generics also, in order to avoid the use of the dangerous any:

export class GenerateThings {
    static *generateSubsets<T>(elements: T[], offset: number = 0): Generator<T[], void, void> {
        // ...
    }
}

Btw, I don't think your code will work quite correctly as it stands, I suspect when you said const first = elements[offset]; you meant let first = elements[offset ];

  • Related