Skip to content
Open
Show file tree
Hide file tree
Changes from 43 commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
9cda493
feat: init `Filter` type
benzaria Jun 10, 2025
a56ed2c
feat: add extra tests, refactor type for readability, add extra condi…
benzaria Jun 10, 2025
c100e9c
Merge branch 'sindresorhus:main' into Filter
benzaria Jun 10, 2025
80404b5
refactor: improve JSDoc links and clean up test cases for ArrayFilter
benzaria Jun 10, 2025
20dffe3
Merge branch 'origin/Filter' into Filter
benzaria Jun 10, 2025
640cb4f
feat: fix `IsLeadingRestElement` & add `IsTrailingRestElement`
benzaria Jun 10, 2025
26e2b0c
Remake the `ArrayFilter` type and cleanup unused types
benzaria Jun 20, 2025
416d35a
fix: test errors
benzaria Jun 20, 2025
d10b19e
Merge branch 'main' into Filter
benzaria Jun 20, 2025
d4b89c2
Merge branch 'main' into Filter
benzaria Jun 20, 2025
c00320b
reverte: changes on `IsUnion`
benzaria Jun 24, 2025
691b9a1
feat: add `strict` option to `Filter`
benzaria Jun 24, 2025
d4fb6ae
improve: added types for `Filter`
benzaria Jun 24, 2025
f32aed0
test: fix test errors
benzaria Jun 24, 2025
67ae5b8
improve: `ObjectFilter`
benzaria Jun 24, 2025
8b13bea
Update array.d.ts
sindresorhus Aug 24, 2025
3d2baa7
Update filter.d.ts
sindresorhus Aug 24, 2025
d8e2a57
Merge remote-tracking branch 'upstream/main' into Filter
benzaria Sep 23, 2025
2eb53d0
Merge branch 'origin/Filter' into Filter
benzaria Sep 23, 2025
97969ae
feat: improve `Filter` type, test and docs, add test and docs for `Ob…
benzaria Sep 23, 2025
022e082
doc: add examples for `strict` option
benzaria Sep 23, 2025
6498c01
Merge branch 'main' into Filter
benzaria Sep 27, 2025
c24f3a7
add `export {}` to `Filter`
benzaria Sep 27, 2025
af04729
add `export {}` to `ObjectFilter`
benzaria Sep 27, 2025
ed8646f
fix: export errors
benzaria Sep 27, 2025
5dcaa2b
refactor: `ObjectFIlter` test
benzaria Sep 27, 2025
2502eef
Update readme.md
sindresorhus Oct 10, 2025
9c29c46
Update filter.d.ts
sindresorhus Oct 10, 2025
92aba18
Update type.d.ts
sindresorhus Oct 10, 2025
b88b1e1
Update object-filter.d.ts
sindresorhus Oct 10, 2025
29eb5e5
`Filter`: add preserve readonly modifier, fix JsDoc example, add some…
benzaria Oct 10, 2025
7b2cd09
`FilterObject`: rename type, some refactoring
benzaria Oct 10, 2025
9cb21a0
minor changes
benzaria Oct 10, 2025
3c606dd
Merge branch 'origin/Filter' into Filter
benzaria Oct 10, 2025
a89d8bd
fix `CleanEmpty` error
benzaria Oct 10, 2025
b2dc2be
Merge branch 'main' into Filter
benzaria Oct 17, 2025
9984532
feat: merge `FilterObject` to `Filter`
benzaria Oct 19, 2025
58654b0
docs: fix JsDoc examples
benzaria Oct 21, 2025
10477ba
Update filter.d.ts
sindresorhus Oct 24, 2025
11a0b22
Fix grammar in FilterObject and FilterArray comments
sindresorhus Oct 24, 2025
2f5541f
Update array.d.ts
sindresorhus Oct 24, 2025
6a9b4b7
Update filter.d.ts
sindresorhus Oct 24, 2025
bd1a9bb
Fix duplicate lines in Extends type documentation
sindresorhus Oct 24, 2025
3a4b48b
Update type.d.ts
sindresorhus Oct 24, 2025
9d80cf1
minor comments change
benzaria Oct 24, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ export type {ArrayValues} from './source/array-values.d.ts';
export type {ArraySlice} from './source/array-slice.d.ts';
export type {ArraySplice} from './source/array-splice.d.ts';
export type {ArrayTail} from './source/array-tail.d.ts';
export type {Filter, FilterOptions} from './source/filter.d.ts';
export type {ArrayElement} from './source/array-element.d.ts';
export type {SetFieldType, SetFieldTypeOptions} from './source/set-field-type.d.ts';
export type {Paths, PathsOptions} from './source/paths.d.ts';
Expand Down
5 changes: 3 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,9 @@ Click the type names for complete docs.
- [`IntClosedRange`](source/int-closed-range.d.ts) - Generate a union of numbers (includes the start and the end).
- [`ArrayIndices`](source/array-indices.d.ts) - Provides valid indices for a constant array or tuple.
- [`ArrayValues`](source/array-values.d.ts) - Provides all values for a constant array or tuple.
- [`ArraySplice`](source/array-splice.d.ts) - Create a new array type by adding or removing elements at a specified index range in the original array.
- [`ArrayTail`](source/array-tail.d.ts) - Extract the type of an array or tuple minus the first element.
- [`ArraySplice`](source/array-splice.d.ts) - Creates a new array type by adding or removing elements at a specified index range in the original array.
- [`ArrayTail`](source/array-tail.d.ts) - Extracts the type of an array or tuple minus the first element.
- [`Filter`](source/filter.d.ts) - Filters elements or properties from an array or object based on whether they extend the specified filter type.
- [`SetFieldType`](source/set-field-type.d.ts) - Create a type that changes the type of the given keys.
- [`Paths`](source/paths.d.ts) - Generate a union of all possible paths to properties in the given object.
- [`SharedUnionFields`](source/shared-union-fields.d.ts) - Create a type with shared fields from a union of object types.
Expand Down
196 changes: 196 additions & 0 deletions source/filter.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
import type {IsTruthy, Extends, IsAnyOrNever} from './internal/type.d.ts';
import type {CleanEmpty, IsArrayReadonly} from './internal/array.d.ts';
import type {ApplyDefaultOptions} from './internal/index.d.ts';
import type {IsOptionalKeyOf} from './is-optional-key-of.d.ts';
import type {UnknownRecord} from './unknown-record.d.ts';
import type {UnknownArray} from './unknown-array.d.ts';
import type {Simplify} from './simplify.d.ts';
import type {If} from './if.d.ts';

/**
{@link Filter `Filter`} options.
*/
export type FilterOptions = {
/**
Controls the strictness of type checking when filtering.

- 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

@example
```
import type {Filter} from 'type-fest';

type T1 = Filter<[1, 2, 3 | 4, 3?, 4?], 3>;
//=> [3 | 4, 3?]

type T2 = Filter<[1, 2, 3 | 4, 3?, 4?], 3, {strict: true}>;
//=> [3?]

type T3 = Filter<{a: 1; b: 2; c: 3 | 4; d?: 3; e?: 4}, 3>;
//=> {c: 3 | 4; d?: 3}

type T4 = Filter<{a: 1; b: 2; c: 3 | 4; d?: 3; e?: 4}, 3, {strict: true}>;
//=> {d?: 3}
```
*/
strict?: boolean;
};

type DefaultFilterOptions = {
strict: false;
};

/**
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 or properties from an array or object based on whether they extend the specified filter type.

If `FilterType` is `Boolean`, it filters out `falsy` values like {@link Boolean `Boolean(T)`} does.

Optional control for strict or loose type comparison.

@example
```
import type {Filter} from 'type-fest';

type A1 = Filter<[1, 2, 3 | 4, 3?, 4?], 3>;
//=> [3 | 4, 3?]

type A2 = Filter<[1, 2, 3 | 4, 3?, 4?], 3, {strict: true}>;
//=> [3?]

type A3 = Filter<['foo1', 'bar2', 'fooo', 'foo3'], `foo${number}`>;
//=> ['foo1', 'foo3']

type A4 = Filter<[1, '2', 3, 'foo', false], string | number>;
//=> [1, '2', 3, 'foo']

type A5 = Filter<[true, false, boolean, 0, 1], Boolean>;
//=> [true, 1]

type A6 = Filter<[0, '', false, null, undefined, 'ok', 42], Boolean>;
//=> ['ok', 42]
```

@example
```
import type {Filter} from 'type-fest';

type O1 = Filter<{a: 1; b: 2; c: 3 | 4; d?: 3; e?: 4}, 3>;
//=> {c: 3 | 4; d?: 3}

type O2 = Filter<{a: 1; b: 2; c: 3 | 4; d?: 3; e?: 4}, 3, {strict: true}>;
//=> {c?: 3}

type O3 = Filter<{a: 'foo1'; b: 'bar2'; c: 'fooo'; d: 'foo3'}, `foo${number}`>;
//=> {a: 'foo1'; d: 'foo3'}

type O4 = Filter<{a: 1; b: '2'; c: 3; d: 'foo'; e: false}, string | number>;
//=> {a: 1; b: '2'; c: 3; d: 'foo'}

type O5 = Filter<{a: true; b: false; c: boolean; d: 0; e: 1}, Boolean>;
//=> {a: true; e: 1}

type O6 = Filter<{a: 0; b: ''; c: false; d: null; e: undefined; f: 'ok'; g: 42}, Boolean>;
//=> {f: 'ok'; g: 42}
```

@category Array
@category Object
*/
export type Filter<
BaseType extends UnknownArray | UnknownRecord,
FilterType,
Options extends FilterOptions = {},
> = IsAnyOrNever<BaseType> extends true ? BaseType
: ApplyDefaultOptions<
FilterOptions,
DefaultFilterOptions,
Options
> extends infer ResolvedOptions extends Required<FilterOptions>
? CleanEmpty<
BaseType extends UnknownArray
? FilterArray<BaseType, FilterType, ResolvedOptions>
: BaseType extends UnknownRecord
? FilterObject<BaseType, FilterType, ResolvedOptions>
: never
>
: never;

/**
Iterates through the object properties and keeps them if they pass {@link FilterType `FilterType`}.
*/
type FilterObject<
Object_ extends UnknownRecord, Type,
Options extends Required<FilterOptions>,
> = Simplify<{
[Key in keyof Object_ as
FilterType<Object_[Key], Type, Options['strict']> extends true
? Key
: never
]: Object_[Key]
}>;

/**
Iterates through the array elements and keeps them if they pass {@link FilterType `FilterType`}.
*/
type FilterArray<
Array_ extends UnknownArray, Type,
Options extends Required<FilterOptions>,
> =
_FilterArray<Array_, Type, Options> extends infer Result extends UnknownArray
? If<IsArrayReadonly<Array_>, Readonly<Result>, Result> // Preserve readonly modifier
: never;

/**
Core implementation of {@link FilterArray}.
*/
type _FilterArray<
Array_ extends UnknownArray, Type,
Options extends Required<FilterOptions>,
HeadAcc extends UnknownArray = [],
TailAcc extends UnknownArray = [],
> =
keyof Array_ & `${number}` extends never // Is `Array_` a rest element or empty array
? Array_ extends readonly [...infer Rest, infer Last]
// Add `Last` to `TailAcc` if it passes the filter
? _FilterArray<Rest, Type, Options, HeadAcc, [
...IfFilter<FilterType<Last, Type, Options['strict']>, [Last]>,
...TailAcc,
]>
// Handle rest element (spread) or return the final result
: [
...HeadAcc,
...IfFilter<FilterType<Array_[number], Type, Options['strict']>, Array_>,
...TailAcc,
]
: Array_ extends readonly [(infer First)?, ...infer Rest]
// Add `First` to `HeadAcc` if it passes the filter
? _FilterArray<Rest, Type, Options, [
...HeadAcc,
...IfFilter<
FilterType<First, Type, Options['strict']>,
// Preserve optional modifier
If<IsOptionalKeyOf<Array_, 0>, [First?], [First]>
>,
], TailAcc>
: never;
export {};
67 changes: 66 additions & 1 deletion source/internal/array.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type {If} from '../if.d.ts';
import type {IsNever} from '../is-never.d.ts';
import type {OptionalKeysOf} from '../optional-keys-of.d.ts';
import type {EmptyObject} from '../empty-object.d.ts';
import type {UnknownArray} from '../unknown-array.d.ts';
import type {OptionalKeysOf} from '../optional-keys-of.d.ts';
import type {IsExactOptionalPropertyTypesEnabled, IfNotAnyOrNever} from './type.d.ts';

/**
Expand Down Expand Up @@ -87,6 +88,42 @@ Returns whether the given array `T` is readonly.
*/
export type IsArrayReadonly<T extends UnknownArray> = If<IsNever<T>, false, T extends unknown[] ? false : true>;

/**
Represents an empty array, the `[]` or `readonly []` value.
*/
export type EmptyArray = readonly [] | []; // The extra `[]` is just to prevent TS from expanding the type.

/**
Returns a `boolean` for whether the type is an empty array, the `[]` or `readonly []` value.

@example
```
import type {IsEmptyArray} from 'type-fest';

type Pass1 = IsEmptyArray<[]>;
//=> true

type Pass2 = IsEmptyArray<readonly []>;
//=> true

type Fail1 = IsEmptyArray<[0]>;
//=> false

type Fail2 = IsEmptyArray<[0?]>;
//=> false

type Fail3 = IsEmptyArray<...string[]>;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this is valid TS. Ensure all examples are correct.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, I fixed it.

//=> false
```

@see {@link EmptyArray}
@category Array
*/
export type IsEmptyArray<T> =
IsNever<T> extends true ? false
: T extends EmptyArray ? true
: false;

/**
Transforms a tuple type by replacing it's rest element with a single element that has the same type as the rest element, while keeping all the non-rest elements intact.

Expand Down Expand Up @@ -148,4 +185,32 @@ type _CollapseRestElement<
: never // Should never happen, since `[(infer First)?, ...infer Rest]` is a top-type for arrays.
: never; // Should never happen

/**
Cleans any extra empty arrays/objects from a union.

@example
```
type T1 = CleanEmpty<[number] | []>;
//=> [number]

type T2 = CleanEmpty<[number, string?] | [never] | []>;
//=> [number, string?] | [never]

type T3 = CleanEmpty<{a: 'A'} | {}>;
//=> {a: 'A'}

type T4 = CleanEmpty<[]>;
//=> []

type T5 = CleanEmpty<{}>;
//=> {}
```

@category Utilities
*/
export type CleanEmpty<T> =
Exclude<T, EmptyArray | EmptyObject> extends infer U
? IsNever<U> extends true ? T : U
: never;

export {};
34 changes: 34 additions & 0 deletions source/internal/type.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type {If} from '../if.d.ts';
import type {IsAny} from '../is-any.d.ts';
import type {IsNever} from '../is-never.d.ts';
import type {Primitive} from '../primitive.d.ts';
import type {ExtendsStrict} from '../extends-strict.d.ts';

/**
Matches any primitive, `void`, `Date`, or `RegExp` value.
Expand Down Expand Up @@ -129,4 +130,37 @@ export type IsExactOptionalPropertyTypesEnabled = [(string | undefined)?] extend
? false
: true;

/**
Evaluates whether type `T extends U`, using either strict or loose comparison.

- Strict mode, {@link ExtendsStrict `ExtendsStrict<T, U>`} is used.
- Loose mode, {@link ExtendsLoose `ExtendsLoose<T, U>`} is used.
*/
export type Extends<T, U, S extends boolean = false> = {
true: ExtendsStrict<T, U>;
false: ExtendsLoose<T, U>;
}[`${S}`];

/**
Performs a loose type comparison: checks if any of the members in `T` extends `U`.

This is useful when needing to know if any member of `T` extends `U` without returning `boolean`.
*/
export type ExtendsLoose<T, U> = IsNotFalse<T extends U ? true : false>;
// ? Should this type get exposed publicly

/**
Union of `falsy` types in typescript. `never` isn't included.
*/
export type Falsy = 0 | 0n | '' | false | null | undefined; // `| never`

/**
Checks if `T` is **not** {@link Falsy `falsy`} similar to `Boolean(T)`.
*/
// TODO: expose this type publicly
export type IsTruthy<T> =
IsNever<T> extends true ? false
: T extends Falsy ? false
: true;

export {};
Loading