Skip to content
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

Type narrowing of an object does not narrow parent union type containing the object #25631

Closed
Jessidhia opened this issue Jul 13, 2018 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@Jessidhia
Copy link

TypeScript Version: playground

Search Terms: narrowing

Code

enum Type {
  A,
  B
}

interface A {
  type: Type.A
}

interface B {
  type: Type.B
}

type AorB = {
  value: A
} | {
  value: B
  extra: {}
}

declare var aOrB: AorB

if (aOrB.value.type === Type.B) {
  const val: B = aOrB.value // OK
  aOrB.extra // not OK because it's missing in { value: A } but value cannot be A
}

Expected behavior:

The narrowing of aOrB.value to also narrow the type of aOrB.

Actual behavior:

aOrB.extra cannot be accessed because the compiler still believes it can be { value: A } even though value has already been proven to not be A.

Playground Link: https://www.typescriptlang.org/play/index.html#src=enum%20Type%20%7B%0A%20%20A%2C%0A%20%20B%0A%7D%0A%0Ainterface%20A%20%7B%0A%20%20type%3A%20Type.A%0A%7D%0A%0Ainterface%20B%20%7B%0A%20%20type%3A%20Type.B%0A%7D%0A%0Atype%20AorB%20%3D%20%7B%0A%20%20value%3A%20A%0A%7D%20%7C%20%7B%0A%20%20value%3A%20B%0A%20%20extra%3A%20%7B%7D%0A%7D%0A%0Adeclare%20var%20aOrB%3A%20AorB%0A%0Aif%20(aOrB.value.type%20%3D%3D%3D%20Type.B)%20%7B%0A%20%20const%20val%3A%20B%20%3D%20aOrB.value%20%2F%2F%20OK%0A%20%20aOrB.extra%20%2F%2F%20not%20OK%20because%20it's%20missing%20in%20%7B%20value%3A%20A%20%7D%20but%20value%20cannot%20be%20A%0A%7D%0A

@mhegazy
Copy link
Contributor

mhegazy commented Jul 13, 2018

Duplicate of #18758

@mhegazy mhegazy marked this as a duplicate of #18758 Jul 13, 2018
@mhegazy mhegazy added the Duplicate An existing issue was already created label Jul 13, 2018
@typescript-bot
Copy link
Collaborator

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants