Skip to content

Union inference works in only some cases #23312

Closed
@pelotom

Description

@pelotom

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.

Playground Link

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions