I'm trying to create a generic function that returns a random item in an array and properly forwards 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 type signatures for obj1 and obj3 are fine, but for some reason the empty object in the 2nd example causes obj2's signature to get replaced with {}.
- Can you explain why
obj2's signature becomes{}? - Is there a way to work around this?
obj2to be{}in all versions of TS I've tested.{}. I'll edit to correct. I'm still confused, though.