Skip to content
Open
Show file tree
Hide file tree
Changes from 15 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
101 changes: 101 additions & 0 deletions source/filter.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
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;
};

/**
Shorhand 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 extends 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).
*/
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`.
? [First?] // Preserve optional modifier.
: [First]
>,
], TailAcc>
: never;
59 changes: 58 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 @@ -96,6 +97,40 @@ 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 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 @@ -156,3 +191,25 @@ 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<[]>
//=> []
```

@category Utilities
*/
export type CleanEmpty<T> =
Exclude<T, EmptyArray | EmptyObject> extends infer U
? IsNever<U> extends true ? T : U
: never;
35 changes: 34 additions & 1 deletion 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 @@ -100,9 +101,41 @@ type C = IfNotAnyOrNever<never, 'VALID', 'IS_ANY', 'IS_NEVER'>;
export type IfNotAnyOrNever<T, IfNotAnyOrNever, IfAny = any, IfNever = never> =
If<IsAny<T>, IfAny, If<IsNever<T>, IfNever, IfNotAnyOrNever>>;

/*
/**
Indicates the value of `exactOptionalPropertyTypes` compiler option.
*/
export type IsExactOptionalPropertyTypesEnabled = [(string | undefined)?] extends [string?]
? 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 wheither 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 get exposed publicly

/**
A union of `falsy` types in JS.
*/
export type Falsy = 0 | 0n | '' | false | null | undefined; // `| never`

/**
Checks if `T` is **not** {@link Falsy `falsy`} similar to `Boolean(T)`.
*/
export type IsTruthy<T> =
IsNever<T> extends true ? false
: T extends Falsy ? false
: true; // ? Should this get exposed publicly
29 changes: 29 additions & 0 deletions source/object-filter.d.ts
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]
}>;
115 changes: 115 additions & 0 deletions test-d/filter.ts
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]);