Search code examples
javascriptnode.jstypescriptgenerator

How to declare yield type of generator with TypeScript


I have this generator function which yields random values from an array:

export const fisherYatesShuffle = function* <T>(deck: Array<T>) : Generator<T, void, T> {
    for (let i = deck.length - 1; i >= 0; i--) {
        const swapIndex = Math.floor(Math.random() * (i + 1));
        [deck[i], deck[swapIndex]] = [deck[swapIndex], deck[i]];
        yield deck[i];
    }
};

when I iterate over it:

for(const V of fisherYatesShuffle<string>(['a','b','c'])){
  // typeof V here should be string
}

but TS doesn't seem to know that V is a string.

anyone know if there is a fix?


Solution

  • Your return type is wrong.

    You can use

    • Generator<T, void, unknown> which is what the compiler infers
    • Generator<T, void, T | undefined since next() can also return undefined

    Playground