Skip to content

narrowing in switches doesnt work on constrained unions #20375

Closed
@zpdDG4gta8XKpMCd

Description

@zpdDG4gta8XKpMCd

assuming my understanding it right: an extended union is a subset (subtype) of the original union

    declare function never(never: never): never;
    type X = 'A' | 'B' | 'C';
    void function fn<Y extends X>(y: Y): Y {
        switch (y) {
            case 'A': return y;
            case 'B': return y;
            case 'C': return y;
            default: return never(y); // <-- y expected to be never, actual Y
        }
    }

same problem with objects

    type X = { k: 'A' } | { k: 'B' } | { k: 'C' };
    void function fn<Y extends X>(y: Y): Y {
        switch (y.k) {
            case 'A': return y;
            case 'B': return y;
            case 'C': return y;
            default: return never(y); // <-- y expected to be never, actual Y
        }
    }

Activity

masaeedu

masaeedu commented on Nov 30, 2017

@masaeedu
Contributor

Nvm earlier comment, misunderstood what you meant by "extended". The weird part here is y is being inferred as never in each of the 'A', 'B' and 'C' cases.

mhegazy

mhegazy commented on Dec 2, 2017

@mhegazy
Contributor

Generics that are constrained to literal types are not treated like literals at the moment. generics have a more conservative behavior when narrowing in general since the actual type is not known, but generics with literal constraints should be behave like a union of literals.

added
BugA bug in TypeScript
SuggestionAn idea for TypeScript
and removed
BugA bug in TypeScript
on Dec 2, 2017
sandersn

sandersn commented on Dec 4, 2017

@sandersn
Member

In the first example, y is never in the case A/B/C branches. This, too , seems wrong.

declare var n: never;
function fn<Y extends "A" | "B" | "C">(y: Y): Y {
    switch (y) {
        case 'A': n = y; return y; // ok!
        case 'B': n = y; return y;
        case 'C': n = y; return y;
        default: n = y; return never(y); // <-- y expected to be never, actual Y
    }
}
added
BugA bug in TypeScript
and removed
SuggestionAn idea for TypeScript
on Jan 30, 2018
added this to the TypeScript 2.8 milestone on Jan 30, 2018
RyanCavanaugh

RyanCavanaugh commented on Jan 30, 2018

@RyanCavanaugh
Member

This is indeed super wrong

24 remaining items

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

      Participants

      @jcalz@sandersn@marshall007@zpdDG4gta8XKpMCd@masaeedu

      Issue actions

        narrowing in switches doesnt work on constrained unions · Issue #20375 · microsoft/TypeScript