Skip to content

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

Closed
@NoelAbrahams

Description

@NoelAbrahams

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.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions