Looking to develop a versatile function that can pick a random element from an array while maintaining type information using Typescript 2.6.2.
function sample<T>(array: T[]) : T {
const index = Math.floor(Math.random() * array.length);
return array[index];
}
const obj1 = sample([1, 'a', Symbol('sym')]);
// const obj1: number | string | symbol
const obj2 = sample([1, 'a', Symbol('sym'), {}]);
// const obj2: {}
const obj3 = sample([1, 'a', Symbol('sym'), {a: 'a'}]);
// const obj3: number | string | symbol | {a:string}
The expected types for obj1
and obj3
are correct, however in the case of obj2
, including an empty object seems to cause its signature to be replaced with just {}
.
- Can you explain why the type signature of
obj2
is showing as{}
? - Is there any way to resolve this issue?