Skip to content

Control flow analysis: switch (true) case #8934

Closed

Description

TypeScript Version:

1.9.0-dev

Code

// A self-contained demonstration of the problem follows...
interface A {}
interface B {}
interface C {}
declare function isA(arg: any): arg is A;
declare function isB(arg: any): arg is B;
declare function isC(arg: any): arg is C;

function handleAction<T>(action: T) {
  switch (true) {
    case isA(action):
    case isB(action):
      // action expected to be A|B type here
      break;
    case isC(action):
      // action expected to be C type here
      break;
    default:
      // action expected to be undefined type here
  }
}

Activity

  1. sandersn commented on Oct 13, 2016

    @sandersn
    Member

    Unfortunately, the switch code uses a form that is not recognised as a narrowing form. switch is really only used to narrow discriminated unions:

    function f(x: First | Second | Third) {
      switch(x.kind) {
        case Kind.First:
          x; // x is now First
          break;
          // etc
      }
    }

    Note that even if you rewrite to if, not all expressions are usable for narrowing. For example,

    if (true === isA(action)) {
      action; // action is not narrowed
    }
    if (isA(action)) {
      action; // action is narrowed to A
    }

    In order to keep things simple, narrowing only supports a few common syntactic forms. We do expand this list from time to time, but I don't think the switch (true) pattern is common enough to make it on the list.

  2. added
    Working as Intended
    on Oct 13, 2016
  3. added
    Suggestion
    In Discussion
    and removed
    Bug
    Working as Intended
    on Oct 13, 2016
  4. added
    Won't Fix
    and removed
    In Discussion
    on Nov 15, 2016
  5. RyanCavanaugh commented on Nov 15, 2016

    @RyanCavanaugh
    Member

    Not a common enough pattern to support

  6. locked and limited conversation to collaborators on Jun 19, 2018
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

    SuggestionWon't Fix

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions