Skip to content

Type guards fail in switch (true) constructs. #16887

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
sccolbert opened this issue Jul 2, 2017 · 1 comment
Closed

Type guards fail in switch (true) constructs. #16887

sccolbert opened this issue Jul 2, 2017 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@sccolbert
Copy link

Sometimes it's nice to use switch (true) along with boolean expression case clauses to make code cleaner than a bunch of if/else statements. Unfortunately, type guards do not work here:

TypeScript Version: 2.3.1

Code

interface Square {
  type: 'square';
  size: number;
}

interface Rectangle {
  type: 'rectangle';
  width: number;
  height: number;
}

type Shape = Square | Rectangle;

function isSquare(shape: Shape): shape is Square {
  return shape.type === 'square';
}

function isRectangle(shape: Shape): shape is Rectangle {
  return shape.type === 'rectangle';
}


let shape: Shape;

switch (true) {
  case shape.type === 'square':
    shape.size;  // fail
    break;
  case shape.type === 'rectangle':
    shape.width; // fail
    break;
}


switch (true) {
  case isSquare(shape):
    shape.size;  // fail
    break;
  case isRectangle(shape):
    shape.width; // fail
    break;
}


switch (shape.type) {
  case 'square':
    shape.size;  // okay
    break;
  case 'rectangle':
    shape.width; // okay
    break;
}


if (isSquare(shape)) {
  shape.size;  // okay
}

if (isRectangle(shape)) {
  shape.width;  // okay
  shape.height; // okay
}

Expected behavior:

All forms should compile.

Actual behavior:

The switch (true) forms do not compile.

@yortus
Copy link
Contributor

yortus commented Jul 2, 2017

Duplicate of #8934

@rbuckton rbuckton added the Duplicate An existing issue was already created label Aug 5, 2017
@rbuckton rbuckton closed this as completed Aug 5, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants