TypeScript Version: 2.8.0-dev.20180316
Search Terms:
- union type inference array
- union type filter undefined
Code
letx: string|undefined;if(typeofx!=='string'){x='foo';}constresult=['foo','bar'].indexOf(x)!==-1;constelem=[['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
TypeScript Version: 2.8.0-dev.20180316
Search Terms:
Code
Compiled with
--strictNullChecksExpected behavior:
It should pass. The first
indexOfinfersxasstringcorrectly, the second one doesn't, even though there is no async operation in the meantime and no mutation in thefiltercallback.Actual behavior:
It errors on the second
indexOf: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
strictNullChecksthere.Related Issues:
#16069, #18562