This is the code. Got the idea from this answer.
I'm using the generic type parameter: T extends unknown[]
, since this function should work for any kind of array.
export const pickRandomItems = <T extends unknown[]> (arr: T, n: number): T => {
const shuffled = Array.from(arr).sort(() => 0.5 - Math.random());
return shuffled.slice(0, n);
};
But I'm getting the following error on the return
statement:
It goes away if I do a type assertion. But why is that necessary? Am I doing something wrong?
NOTE:
The following line is evaluated as unknown[]
, so why is the type assertion necessary anyway?
const result = shuffled.slice(0, n);