Skip to content

Unexpected literal union type widening in generic type inference #32596

Closed
@ulrichb

Description

@ulrichb

TypeScript Version: 3.5.1

Search Terms: type widening generic union inference

Code

function example() {

    type SomeUnion = "A" | "B" | "C";

    function fun<T extends SomeUnion>(x: T, y: T) { }

    fun("A", "A");  // no error

    fun("A", "B");  // !!! no error because widening to "A" | "B"
    fun("B", "A");  // !!! no error because widening to "A" | "B"
}


function counterexample() {

    type SomeUnion = string | number | boolean;

    function fun<T extends SomeUnion>(x: T, y: T) { }

    fun("str", "other");  // no error
    fun("str", 42);       // error as expected
    fun(42, "str");       // error as expected
}

Expected behavior:
Compile errors in the two "!!!" marked lines.

Actual behavior:
No compile error, instead the type inference inferred "A" | "B" for T.

That's pretty unexpected and IMO a bug, because for literal type parameters it makes no sense to infer any union, it obviously can only be one value (therefor the type widening should stop when seeing a parameter which is directly the generic literal union type).

Also it's asymmetric with non literal union types (see counterexample).

Playground Link: Here

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