Description
openedon 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.