-
-
Notifications
You must be signed in to change notification settings - Fork 625
Add Filter
type
#1183
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
Open
benzaria
wants to merge
17
commits into
sindresorhus:main
Choose a base branch
from
benzaria:Filter
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add Filter
type
#1183
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
9cda493
feat: init `Filter` type
benzaria a56ed2c
feat: add extra tests, refactor type for readability, add extra condi…
benzaria c100e9c
Merge branch 'sindresorhus:main' into Filter
benzaria 80404b5
refactor: improve JSDoc links and clean up test cases for ArrayFilter
benzaria 20dffe3
Merge branch 'origin/Filter' into Filter
benzaria 640cb4f
feat: fix `IsLeadingRestElement` & add `IsTrailingRestElement`
benzaria 26e2b0c
Remake the `ArrayFilter` type and cleanup unused types
benzaria 416d35a
fix: test errors
benzaria d10b19e
Merge branch 'main' into Filter
benzaria d4b89c2
Merge branch 'main' into Filter
benzaria c00320b
reverte: changes on `IsUnion`
benzaria 691b9a1
feat: add `strict` option to `Filter`
benzaria d4fb6ae
improve: added types for `Filter`
benzaria f32aed0
test: fix test errors
benzaria 67ae5b8
improve: `ObjectFilter`
benzaria 8b13bea
Update array.d.ts
sindresorhus 3d2baa7
Update filter.d.ts
sindresorhus File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
import type {ApplyDefaultOptions} from './internal/object.d.ts'; | ||
import type {OptionalKeysOf} from './optional-keys-of.d.ts'; | ||
import type {IsTruthy, Extends} from './internal/type.d.ts'; | ||
import type {UnknownArray} from './unknown-array.d.ts'; | ||
import type {CleanEmpty} from './internal/array.d.ts'; | ||
import type {IsAny} from './is-any.d.ts'; | ||
|
||
/** | ||
Filter options. | ||
|
||
@see {@link Filter `Filter`} | ||
*/ | ||
type FilterOptions = { | ||
/** | ||
Controls the strictness of type checking in {@link FilterType `FilterType`}. | ||
|
||
- When `true`, the entire union type **must** extend the filter type. For example, `string | number extends string` returns `false`. | ||
- When `false`, the check passes if **any** member of the union extends the filter type. For example, `string | number extends string` returns `true`. | ||
|
||
@default false | ||
*/ | ||
strict?: boolean; | ||
}; | ||
|
||
type DefaultFilterOptions = { | ||
strict: false; | ||
}; | ||
|
||
/** | ||
Shorthand for `ApplyDefaultOptions<...>` | ||
*/ | ||
export type ApplyFilterOptions<Options extends FilterOptions> = | ||
ApplyDefaultOptions< | ||
FilterOptions, | ||
DefaultFilterOptions, | ||
Options | ||
>; | ||
|
||
/** | ||
Returns a boolean for whether a value `T` extends the filtering type `U`. | ||
|
||
If `U` is `Boolean`, it checks whether `T` is `truthy` like {@link Boolean `Boolean(T)`} does. | ||
|
||
Otherwise, it uses {@link Extends `Extends<T, U, S>`} to check if `T extends U` with strict or loose mode. | ||
*/ | ||
type FilterType<T, U, S extends boolean> = | ||
Boolean extends U | ||
? IsTruthy<T> | ||
: Extends<T, U, S>; | ||
|
||
/** | ||
Determines whether the array `V` should be kept based on the boolean type `T`. | ||
*/ | ||
type IfFilter<T extends boolean, V extends UnknownArray> = [T] extends [true] ? V : []; | ||
|
||
/** | ||
Filters elements from an array based on whether they extend the given type. | ||
|
||
If `Type` is `Boolean`, it filters out `falsy` values like {@link Boolean `Boolean(T)`} does. | ||
|
||
Strict controls whether strict or loose type comparison is used (defaults to loose). | ||
|
||
@category Array | ||
@category Utilities | ||
*/ | ||
export type Filter< | ||
Array_ extends UnknownArray, Type, | ||
Options extends FilterOptions = {}, | ||
> = IsAny<Array_> extends true ? [] | ||
: CleanEmpty<_Filter<Array_, Type, ApplyFilterOptions<Options>['strict']>>; | ||
|
||
/** | ||
Internal implementation of {@link Filter}. | ||
|
||
Iterates through the array and includes elements in the accumulator if they pass `FilterType`. | ||
*/ | ||
type _Filter< | ||
Array_ extends UnknownArray, Type, | ||
Strict extends boolean = false, | ||
HeadAcc extends any[] = [], | ||
TailAcc extends any[] = [], | ||
> = | ||
keyof Array_ & `${number}` extends never // Is `Array_` leading a rest element or empty | ||
? Array_ extends readonly [...infer Rest, infer Last] | ||
? _Filter<Rest, Type, Strict, HeadAcc, [ | ||
...IfFilter<FilterType<Last, Type, Strict>, [Last]>, | ||
...TailAcc, | ||
]> | ||
: [ | ||
...HeadAcc, | ||
...IfFilter<FilterType<Array_[number], Type, Strict>, Array_>, | ||
...TailAcc, | ||
] | ||
: Array_ extends readonly [(infer First)?, ...infer Rest] | ||
? _Filter<Rest, Type, Strict, [ | ||
...HeadAcc, | ||
...IfFilter<FilterType<First, Type, Strict>, | ||
'0' extends OptionalKeysOf<Array_> // TODO: replace with `IsOptionalKeyOf`. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This can be done now. |
||
? [First?] // Preserve optional modifier. | ||
: [First] | ||
>, | ||
], TailAcc> | ||
: never; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import type {FilterOptions, FilterType, ApplyFilterOptions} from './filter.d.ts'; | ||
import type {UnknownRecord} from './unknown-record.d.ts'; | ||
import type {CleanEmpty} from './internal/array.d.ts'; | ||
import type {Simplify} from './simplify.d.ts'; | ||
import type {IsAny} from './is-any.d.ts'; | ||
|
||
/** | ||
Filters properties from an object where the property value matches the given type. | ||
|
||
If `Type` is `Boolean`, it filters out `falsy` values like `Boolean(T)` does. | ||
|
||
Strict controls whether strict or loose type comparison is used (defaults to loose). | ||
*/ | ||
type ObjectFilter< | ||
Object_ extends UnknownRecord, Type, | ||
Options extends FilterOptions = {}, | ||
> = IsAny<Object_> extends true ? {} | ||
: CleanEmpty<_ObjectFilter<Object_, Type, ApplyFilterOptions<Options>['strict']>>; | ||
|
||
export type _ObjectFilter< | ||
Object_ extends UnknownRecord, Type, | ||
Strict extends boolean = false, | ||
> = Simplify<{ | ||
[Key in keyof Object_ as | ||
FilterType<Object_[Key], Type, Strict> extends true | ||
? Key | ||
: never | ||
]: Object_[Key] | ||
}>; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
import {expectType} from 'tsd'; | ||
import type {Filter} from '../source/filter.d.ts'; | ||
|
||
// Basic loose filtering | ||
expectType<Filter<[1, 2, 3, 3, 4], 3, {strict: true}>>([3, 3]); | ||
expectType<Filter<[1, '2', 3, 'foo', false], number>>([1, 3]); | ||
expectType<Filter<[1, '2', 3, 'foo', false], string>>(['2', 'foo']); | ||
expectType<Filter<[1, '2', 3, 'foo', false], string | number>>([1, '2', 3, 'foo']); | ||
expectType<Filter<['foo', 'baz', 'foo', 'foo'], 'foo', {strict: true}>>(['foo', 'foo', 'foo']); | ||
expectType<Filter<[1, '2', 3, 'foo', false], string | number, {strict: true}>>([1, '2', 3, 'foo']); | ||
expectType<Filter<['1', '2', 3, 4, 'foo'], `${number}`>>(['1', '2']); | ||
expectType<Filter<[true, false, true, 0, 1], boolean>>([true, false, true]); | ||
expectType<Filter<[true, false, true, 0, 1], true>>([true, true]); | ||
|
||
// Filtering Boolean (keep truthy values) | ||
expectType<Filter<[true, false, boolean, 0, 1], Boolean>>([true, 1]); | ||
expectType<Filter<[true, false, boolean, 0, 1], Boolean, {strict: true}>>([true, 1]); | ||
expectType<Filter<[0, '', false, null, undefined, 'ok', 42], Boolean>>(['ok', 42]); | ||
expectType<Filter<[true, false, 0, 1, '', 'text', null, undefined], Boolean>>([true, 1, 'text']); | ||
|
||
// Filtering objects | ||
type Object1 = {a: number}; | ||
type Object2 = {b: string}; | ||
expectType<Filter<[Object1, Object2, Object1 & Object2], Object1>>({} as [Object1, Object1 & Object2]); | ||
expectType<Filter<[Object1, Object2, Object1 & Object2], Object1, {strict: true}>>({} as [Object1, Object1 & Object2]); | ||
|
||
// Loose filtering by boolean or number | ||
expectType<Filter<[true, 0, 1, false, 'no'], boolean | number>>([true, 0, 1, false]); | ||
|
||
// Filtering array containing null | undefined | string | ||
expectType<Filter<[null, undefined, 'foo', ''], string>>(['foo', '']); | ||
|
||
// Filtering with unknown type (should keep everything) | ||
expectType<Filter<[1, 'a', true], unknown>>([1, 'a', true]); | ||
|
||
// Filtering with any type (should keep everything) | ||
expectType<Filter<[1, 'a', true], any>>([1, 'a', true]); | ||
|
||
// Filtering with never type (should remove everything) | ||
expectType<Filter<[1, 2, 3], never>>([]); | ||
// ? Shoud we change this behavior ? | ||
|
||
// Filtering array of arrays by array type | ||
expectType<Filter<[[number], string[], number[]], number[]>>([[1], [2, 3]]); | ||
|
||
// Filtering by a union including literal and broader type | ||
expectType<Filter<[1, 2, 3, 'foo', 'bar'], 1 | string>>([1, 'foo', 'bar']); | ||
|
||
// Filtering complex nested union types | ||
type Nested = {x: string} | {y: number} | null; | ||
expectType<Filter<[ {x: 'a'}, {y: 2}, null, {z: true} ], Nested>>([{x: 'a'}, {y: 2}, null]); | ||
|
||
// Filtering with boolean type but array has no boolean values | ||
expectType<Filter<[1, 2, 3], Boolean>>([1, 2, 3]); | ||
|
||
// Filtering with boolean type but array has falsy values | ||
expectType<Filter<[0, '', false, null, undefined], Boolean>>([]); | ||
|
||
// Filtering string literals with template literal union | ||
expectType<Filter<['foo1', 'bar2', 'foo3'], `foo${number}`>>(['foo1', 'foo3']); | ||
|
||
// Filtering with `Boolean` type but including custom objects with truthy/falsy behavior | ||
class Foo {} | ||
expectType<Filter<[typeof Foo, {}, null, undefined], Boolean>>([Foo, {}]); | ||
|
||
// Filtering with strict = true and union including literals and primitives | ||
expectType<Filter<[1, '1', 2, '2', true, false], number | `${number}`, {strict: true}>>([1, '1', 2, '2']); | ||
|
||
// Filtering falsy values mixed with ({} | [] is truthy) | ||
expectType<Filter<[false, 0, '', null, undefined, {}, []], Boolean>>([{}, []]); | ||
|
||
// Filtering with `true` literal (strict) but array contains boolean and number | ||
expectType<Filter<[true, false, 1, 0], true, {strict: true}>>([true]); | ||
|
||
// Filtering empty string literal type with strict mode | ||
expectType<Filter<['', 'non-empty'], '', {strict: true}>>(['']); | ||
|
||
// Filtering with loose mode for literal union type and matching subset | ||
expectType<Filter<[1, 2, 3, 4, 5], 2 | 3>>([2, 3]); | ||
|
||
// Filtering tuples with mixed optional and required elements | ||
type Tuple = [string, number?, boolean?]; | ||
expectType<Filter<Tuple, number>>({} as [number?]); | ||
expectType<Filter<Tuple, string | boolean>>({} as [string, boolean?]); | ||
|
||
// Rest elements | ||
expectType<Filter<['f', ...string[], 's'], string>>({} as ['f', ...string[], 's']); | ||
expectType<Filter<['f', ...string[], 's'], 'f' | 's'>>({} as ['f', 's']); | ||
expectType<Filter<[string, ...string[]], string>>({} as [string, ...string[]]); | ||
expectType<Filter<[string, ...string[], number], string>>({} as [string, ...string[]]); | ||
|
||
// Rest and Optional | ||
expectType<Filter<[true, number?, ...string[]], string>>({} as string[]); | ||
expectType<Filter<[true, number?, ...string[]], number | string>>({} as [number?, ...string[]]); | ||
expectType<Filter<[string?, ...string[]], number | string>>({} as [string?, ...string[]]); | ||
|
||
// Union | ||
expectType<Filter<[1, '2', 3, false] | ['1', 2, '3', true], number>>({} as [1, 3] | [2]); | ||
expectType<Filter<[1, '2', 3, false] | ['1', 2, '3', true], string>>({} as ['2'] | ['1', '3']); | ||
expectType<Filter<[true, number?, ...string[]] | [false?, ...Array<'foo'>], string>>({} as string[] | Array<'foo'>); | ||
expectType<Filter<[true, number?, ...string[]] | [false?, ...Array<'foo'>], number>>({} as [number?]); | ||
|
||
// Edge cases | ||
expectType<Filter<any, any>>({} as []); | ||
expectType<Filter<any, never>>([]); | ||
expectType<Filter<any[], any>>({} as []); | ||
expectType<Filter<any[], never>>({} as any[]); | ||
expectType<Filter<never, any>>({} as never); | ||
expectType<Filter<never, never>>({} as never); | ||
|
||
expectType<Filter<[], number>>([]); | ||
expectType<Filter<[never, never], number>>([]); | ||
expectType<Filter<[never, never], never>>([]); | ||
expectType<Filter<[never, never], never>>([]); | ||
expectType<Filter<[never, never], never, {strict: true}>>({} as [never, never]); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Need proper usage examples.