Skip to content

A type guard for number should narrow also the type for enum values #1718

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
NoelAbrahams opened this issue Jan 18, 2015 · 1 comment · Fixed by #1803
Closed

A type guard for number should narrow also the type for enum values #1718

NoelAbrahams opened this issue Jan 18, 2015 · 1 comment · Fixed by #1803
Assignees
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue

Comments

@NoelAbrahams
Copy link

Hi,

TS Version: 1.4

At present there doesn't appear to be a way to define an enum in a union type and have it narrowed correctly. Here's an example:

function f1(x: number | string){
  if (typeof x === "number") {
    return x + 10;
  }
  else {
      return x.length;
  }
}

enum Colour { red, blue }

function f2(x: Colour | string) {
  if (typeof x === "number") {
    return x + 10; // Error because x is Colour | string
  }
  else {
      return x.length;
  }
}

var x = f1(1);
var y = f2(Colour.blue);

The type guard typeof x === 'number' should probably narrow the type correctly and not report an error in f2.

@ahejlsberg
Copy link
Member

Agreed, that should work as you suggest.

@ahejlsberg ahejlsberg added the Bug A bug in TypeScript label Jan 18, 2015
@ahejlsberg ahejlsberg self-assigned this Jan 18, 2015
@ahejlsberg ahejlsberg added this to the TypeScript 1.5 milestone Jan 18, 2015
@ahejlsberg ahejlsberg added the Fixed A PR has been merged for this issue label Jan 27, 2015
@microsoft microsoft locked and limited conversation to collaborators Jun 18, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants