Below is a function that selects a random item from an array:
const randomFromArray = (array: unknown[]) => {
return array[randomNumberFromRange(0, array.length - 1)];
};
My query pertains to dynamically typing this input instead of resorting to using unknown
or any
. Currently, when the function is called, it naturally returns a type of unknown
, however I desire for it to return the same type as was provided during the call.
For example, when calling
randomFromArray(['red', 'blue']),
the desired returned type is string
, and when calling randomFromArray([1, 2]),
the expected return should be number
.