Skip to content

.filter should narrow down output type #20812

Closed
@ArashMotamedi

Description

@ArashMotamedi

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}.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions