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

Using Array.prototype.filter as a null-guard? #18876

Closed
RonPenton opened this issue Oct 1, 2017 · 3 comments
Closed

Using Array.prototype.filter as a null-guard? #18876

RonPenton opened this issue Oct 1, 2017 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@RonPenton
Copy link

TypeScript Version: 2.4.0

Code

function noNulls(items: (string | null)[]): string[] {
    return items.filter(x => x !== null);   // return type is still (string | null)[]
}

Expected behavior:

Return type from filter should be string[]

Actual behavior:

Return type from filter is (string | null)[].

I know I can get around this by casting the end result, ala:

function noNulls(items: (string | null)[]): string[] {
    return items.filter(x => x !== null) as string[];
}

But that just feels... bad. I'm guessing something like this is insanely complicated, but I figured I'd put this out there in case it isn't.

@jcalz
Copy link
Contributor

jcalz commented Oct 1, 2017

Duplicate of #16069?

@aluanhaddad
Copy link
Contributor

aluanhaddad commented Oct 1, 2017

@jcalz yes.

@RonPenton a slightly more expressive but equally verbose workaround would be to write

function noNulls<T>(items: (T | null)[]) {
    return items.filter((x): x is T => x !== null);
}

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Oct 2, 2017
@mhegazy
Copy link
Contributor

mhegazy commented Oct 17, 2017

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@mhegazy mhegazy closed this as completed Oct 17, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

5 participants