Issue
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 infersGenerator<T, void, T | undefined
sincenext()
can also returnundefined
Answered By - Matthieu Riegler
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.