Skip to content

Generics do not preserve scoped union type of enums #24919

Closed
@trshafer

Description

@trshafer

TypeScript Version: 3.0.0-dev.201xxxxx
I was unable to try this. This is attempted on current playground version (2.8 or 2.9, the playground does not specify)

Search Terms: NonNullable, union

Code

declare function test<T>(condition: T): NonNullable<T>;

enum A {
  ONE,
  TWO,
}

function thing(x: A.ONE) { // or a union type of some of the enum values.
  if (x === A.TWO) {
    // x cannot be A.TWO
  }

  const y = test(x);
  
  if (y === A.TWO) {
    // y can be A.TWO....
  }
}

Expected behavior:
y should not be assignable to A.TWO. y should remain A.ONE type.

Actual behavior:
y becomes type A instead of incoming A.ONE type.

Playground Link:
https://www.typescriptlang.org/play/#src=declare%20function%20test%3CT%3E(condition%3A%20T)%3A%20NonNullable%3CT%3E%3B%0D%0A%0D%0Aenum%20A%20%7B%0D%0A%20%20ONE%2C%0D%0A%20%20TWO%2C%0D%0A%7D%0D%0A%0D%0Afunction%20thing(x%3A%20A.ONE)%20%7B%0D%0A%20%20if%20(x%20%3D%3D%3D%20A.TWO)%20%7B%0D%0A%20%20%20%20%2F%2F%20x%20cannot%20be%20A.TWO%0D%0A%20%20%7D%0D%0A%20%20const%20y%20%3D%20test(x)%3B%0D%0A%20%20%0D%0A%20%20if%20(y%20%3D%3D%3D%20A.TWO)%20%7B%0D%0A%20%20%20%20%2F%2F%20y%20can%20be%20A.TWO....%0D%0A%20%20%7D%0D%0A%7D%0D%0A

Related Issues: #23884 #23046

Thanks for taking a look!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions