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

Union types inferring lost in Array callbacks even with no mutations #22635

Closed
mgol opened this issue Mar 16, 2018 · 2 comments · Fixed by #56908
Closed

Union types inferring lost in Array callbacks even with no mutations #22635

mgol opened this issue Mar 16, 2018 · 2 comments · Fixed by #56908
Labels
Duplicate An existing issue was already created

Comments

@mgol
Copy link

mgol commented Mar 16, 2018

TypeScript Version: 2.8.0-dev.20180316

Search Terms:

  • union type inference array
  • union type filter undefined

Code

let x: string | undefined;
if (typeof x !== 'string') {
  x = 'foo';
}
const result = ['foo', 'bar'].indexOf(x) !== -1;
const elem = [
  ['a', 'foo'],
  ['b', 'qaz'],
].filter(array => array.indexOf(x) !== -1);

Compiled with --strictNullChecks

Expected behavior:
It should pass. The first indexOf infers x as string correctly, the second one doesn't, even though there is no async operation in the meantime and no mutation in the filter callback.

Actual behavior:
It errors on the second indexOf:

test.ts(9,33): error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.

Playground Link:
https://www.typescriptlang.org/play/#src=let%20x%3A%20string%20%7C%20undefined%3B%0D%0Aif%20(typeof%20x%20!%3D%3D%20'string')%20%7B%0D%0A%20%20x%20%3D%20'foo'%3B%0D%0A%7D%0D%0Aconst%20result%20%3D%20%5B'foo'%2C%20'bar'%5D.indexOf(x)%20!%3D%3D%20-1%3B%0D%0Aconst%20elem%20%3D%20%5B%0D%0A%20%20%5B'a'%2C%20'foo'%5D%2C%0D%0A%20%20%5B'b'%2C%20'qaz'%5D%2C%0D%0A%5D.filter(array%20%3D%3E%20array.indexOf(x)%20!%3D%3D%20-1)%3B%0D%0A
You need to enable strictNullChecks there.

Related Issues:
#16069, #18562

@ghost
Copy link

ghost commented Mar 16, 2018

Duplicate of #9998
There is no error if you use a const, as in const x = typeof xIn === "string" ? xIn : "foo";.

@ghost ghost added the Duplicate An existing issue was already created label Mar 16, 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.

@microsoft microsoft locked and limited conversation to collaborators Jul 25, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants