Skip to content

Discriminated switch on generic enum type not inferring correct type #23578

Closed
@oleg-codaio

Description

@oleg-codaio

TypeScript Version: 2.9.0-dev.20180420

Search Terms: discriminated generic enum switch

Code

enum MyEnum {
  ONE = 'one',
  TWO = 'two',
}

interface TypeMap {
  [MyEnum.ONE]: number;
  [MyEnum.TWO]: string;
}

function doAction<T extends MyEnum>(type: T, value: TypeMap[T]): void {
  switch (type) {
    case MyEnum.ONE:
      console.log('type:', type, ', value:', value);
      break;
    case MyEnum.TWO:
      console.log('type:', type, ', value:', value);
      break;
    default:
      console.log('type:', type, ', value:', value);
      break;
  }
}

Expected behavior: the types of type would correspond to MyEnum.ONE / MyEnum.TWO depending on the case, and thus value would also get the expected type.

Actual behavior:: type is still T extends MyEnum even within the discriminated switch statement.

Playground Link: TS Playground

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions