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

Refining one value in a union does not refine all values #30622

Closed
ghost opened this issue Mar 28, 2019 · 3 comments
Closed

Refining one value in a union does not refine all values #30622

ghost opened this issue Mar 28, 2019 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@ghost
Copy link

ghost commented Mar 28, 2019

TypeScript Version: 3.3

Search Terms:

refine union

Code

declare function foo(): [number, string] | [string, number];
const [a, b] = foo();

if (typeof a === 'number') {
  console.log(a, b);
}

Expected behavior:

Would expect b to be of type string here

Actual behavior:

a is refined to number, while b remains string | number

Playground Link:

link

@jack-williams
Copy link
Collaborator

There are two issues at play here:

  1. Narrowings are not tracked across variables like this. The issue for this is: Indirect type narrowing via const #12184

  2. A typeof check will not narrow a union like a discriminant property check, it will only narrow the type of the checked property. This has been the design since CFA was introduced I think, but I don't know if there are any plans to revisit this.

@ghost
Copy link
Author

ghost commented Mar 28, 2019

Is there a different way to either define the return type or do the refinement so that this will work without needing to refine each? Also tried leaving the entire object in tact but that doesn't work either for some reason:

declare function foo(): [number, string] | [string, number];
const res = foo();

if (typeof res[0] === 'number') {
  console.log(res); // [number, string] | [string, number]
}

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Mar 28, 2019
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

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