Closed
Description
TypeScript Version: 2.8.1
Search Terms:
union inference
Code
let result: string | number
// Works
const fromArray = <Z>(cases: Z[]): Z => cases[0];
result = fromArray(['a', 3]);
// Doesn't work
const fromTuple = <Z>(cases: [Z, Z]): Z => cases[0];
result = fromTuple(['a', 3]);
// Doesn't work
const fromVarargs = <Z>(...cases: Z[]): Z => cases[0];
result = fromVarargs('a', 3);
// Works
const fromStringIndex = <Z>(cases: { [k: string]: Z }): Z => cases.x;
result = fromStringIndex({ x: 'a', y: 3 });
// Doesn't work
const fromRecord = <Z>(cases: { [K in 'x' | 'y']: Z }): Z => cases.x;
result = fromRecord({ x: 'a', y: 3 });
Expected behavior:
All of these examples should work, with the type parameter Z
being inferred as the union of the types of all values provided.
Actual behavior:
Only the array and string index cases work.