-
Notifications
You must be signed in to change notification settings - Fork 13.2k
Closed
Labels
DuplicateAn existing issue was already createdAn existing issue was already created
Description
Search Terms
narrow, array, filter
Suggestion
add this overload to Array<T>.filter:
filter(fn: typeof Boolean): Array<Exclude<T, null | undefined | 0 | ''>>This may be considered too specific - but the use case is very common so hopefully worth it.
Use Cases
This will allow using array.filter(Boolean) to get rid of null/undefined/falsy values, and have the type system track it correctly even with strictNullChecks.
Right now the options are to use lodash.compact or write a similar function (not ideal to add a dependency), or to use ! (myArray.filter(Boolean).map(val => val!.foo(...))) which is a little dangerous.
Examples
Example
const maybeStrings = ['foo', null, 'bar']
const definitelyStrings = maybeStrings.filter(Boolean)definitelyStrings is of type (string | null)[] even though it's impossible for nulls to be in it.
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code (I don't think so - types would become more specific)
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
DuplicateAn existing issue was already createdAn existing issue was already created

