Skip to content

Overload Array.filter() to exclude nully when using Boolean #31551

Closed

Description

I want to use Array.filter(Boolean) to filter out falsy values, e.g. nulls and empty strings from a string|null array. The result should be a string array. I am using strict mode (strictNullChecks).

The Array interface could be extended with something like this:

filter(callbackfn: typeof Boolean, thisArg?: any): (NonNullable<T>)[];

TypeScript Version: 3.4.5

Search Terms: array filter boolean narrow

Code

const a1 = ["a", null, "b", ""];
const a2 = a1.filter(Boolean);

Expected behavior:
Type of a2 should be string[].

Actual behavior:
Type of a2 is (string|null)[].

Playground Link: https://www.typescriptlang.org/play/index.html#src=const%20a1%20%3D%20%5B%22a%22%2C%20null%2C%20%22b%22%2C%20%22%22%5D%3B%0D%0Aconst%20a2%20%3D%20a1.filter(Boolean)%3B%0D%0Aconst%20s%20%3D%20a2%5B0%5D.toUpperCase()%3B%0D%0A

Activity

  1. dragomirtitian commented on May 23, 2019

    @dragomirtitian
    Contributor

    Duplicate of #16655 I believe. Which was included and then reverted due to it causing breaking changes. Comment

    This was reverted due to it causing a breaking change in 3.5. The simple repro looks like this:

    declare const Bullean: {
        new(value?: any): Boolean;
        <T>(value?: T): value is Exclude<T, false | null | undefined | '' | 0>;
    };
    
    declare const arr: any[];
    // Was any[], now (3.5) unknown[]
    const arr2 = arr.filter(Bullean);

    There might be something wrong in generic inference, but it's not yet clear. We'll need this scenario to work before adding it back in.

  2. typescript-bot commented on May 25, 2019

    @typescript-bot
    Contributor

    This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

  3. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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