Infer type guard => array.filter(x => !!x) should refine Array<T|null> to Array<T>
See original GitHub issueTypeScript Version: 2.3
Code
const evenSquares: number[] =
[1, 2, 3, 4]
.map(x => x % 2 === 0 ? x * x : null)
.filter(x => !!x);
with strictNullChecks
enabled.
Expected behavior:
This should type check. The type of evenSquares
should be number[]
.
Actual behavior:
The type of evenSquares
is deduced as (number|null)[]
, despite the null values being removed via the call to .filter
.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:522
- Comments:54 (8 by maintainers)
Top Results From Across the Web
TypeScript: Why is that my filter method cannot narrow the ...
filter () which will narrow the type of the array, but it will only use that signature if the compiler recognizes the passed-in...
Read more >Untitled
10-Feb-2019 ES2019 introduces the Array. I'm wondering what the cleanest way is to handle type-checks in union types. filter(). fromValue is a convenience ......
Read more >User Defined Type Guards | Developapa
Narrow down nullable types. It is a common use cases that you have an array of values, and those values can also be...
Read more >0520-new-array-repeat-syntax - The Rust RFC Book
Start Date: 2014-12-13; RFC PR: 520; Rust Issue: 19999. Summary. Under this RFC, the syntax to specify the type of a fixed-length array...
Read more >Inferring and Applying Type Changes - Danny Dig
ABSTRACT. Developers frequently change the type of a program element and update all its references to increase performance, security, or main- tainability.
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
To avoid everybody having to write the same helper functions over and over again I bundled
isPresent
,isDefined
andisFilled
into a helper library:When Typescript bundles this functionality in I’ll remove the package.
To use the library:
To see why this package works please read the readme of the NPM package.
Reopening to track this since both other issues now target lib.d.ts changes