Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
danielrentz opened this issue May 23, 2019 · 2 comments
Closed

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

danielrentz opened this issue May 23, 2019 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@danielrentz
Copy link

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

@dragomirtitian
Copy link
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.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label May 23, 2019
@typescript-bot
Copy link
Collaborator

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants