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

Filter narrowing down its output type without type guards #30863

Closed
TomasHubelbauer opened this issue Apr 11, 2019 · 4 comments
Closed

Filter narrowing down its output type without type guards #30863

TomasHubelbauer opened this issue Apr 11, 2019 · 4 comments
Labels
Duplicate An existing issue was already created

Comments

@TomasHubelbauer
Copy link

TomasHubelbauer commented Apr 11, 2019

I have come across issues such as #7657, #20812 and #20218 as well as SO questions such as this one, but they all deal with type guards.

Could it be made so that the following code:

const items: (number | null)[] = [1,2,3,null];
const numbers = items.filter(i => i !== null);

…just works - infers that numbers is number[] with --strictNullChecks on? I think this should be out of the box behavior with TypeScript and lib.d.ts typings. Is this possible?

@jack-williams
Copy link
Collaborator

Duplicate of #16069

@TomasHubelbauer
Copy link
Author

Indeed, thank you. Hopefully that issue gets more attention soon.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Apr 11, 2019
@jmarceli
Copy link

I was having a similar problem, did you try:

const items: (number | null)[] = [1, 2, 3, null];
const numbers = items.filter((i): i is number => i !== null);

Here is a working example:
https://typescript-play.js.org/#code/MYewdgzgLgBAllApgWwgLhgCjAV2QI0QCcYAfGXAG0oEoBtAXRgF4Y6BGAGhgCZuBmblUoMA3ACgA9JNCRYuAsQgt4SVADoAZnEpIimOCwB88GAEJmrYTXXIAhgAcDx0wCpeNCbOgU8hIsqsCCgQWjp6mAY0GIZwygr+LoYWVjjUNvZOhswmhu48nuLi3iCUiOqUIADm2H5KhUA

@TomasHubelbauer
Copy link
Author

I did end to doing that. I raised this issue to see if there is a future where we won't have to spell this out to the compiler. Looks like the mentioned issue is tracking the progress towards that.

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