Closed
Description
TypeScript Version: 2.6.2
The output of filter
can be a further constrained/narrowed-down type. For example, you can use filter
to find items in an array that have a certain property. TS is great at inferring these constraints within the filter predicate, but should also carry the inference forward into filter
results. See usage of filter
and map
in the example below:
Code
interface A { text?: string }
let array: A[] = [{}, {text: "hello"}, {}, {text: "world"}];
let lengths = array.filter(e => e.text).map(e => e.text.length);
^^^^^^
// [ts] Object is possibly 'undefined'.
// (property) A.text: string | undefined
Expected behavior:
The output type of filter
should be {text: string}
because TS correctly understands the filter predicate: only elements with text
property are returned.
Actual behavior:
The type output of filter
is still {text?: string}
.