Skip to content
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

Add function override, support narrowing when using a type guard as the resolver function #585

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 3 additions & 1 deletion packages/array-partition/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,6 @@
* partition(['a', 1, 2, 'b'], x => typeof x == 'string');
* // => [['a', 'b'], [1, 2]]
*/
export default function partition<T>(arr: T[], resolver: (arg: T) => boolean): [T[], T[]]
declare function partition<T, S extends T>(arr: T[], resolver: (arg: T) => arg is S): [S[], Exclude<T, S>[]];
declare function partition<T>(arr: T[], resolver: (arg: T) => boolean): [T[], T[]]
export default partition;
9 changes: 8 additions & 1 deletion packages/array-partition/index.tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ import partition from './index';

// OK
const test1: [number[], number[]] = partition([1, 5, 2, 4, 3], n => n > 3);
const test2: [string[], number[]] = partition(['a', 2, 3, '3'], x => typeof x == 'string') as [string[], number[]]; //if you know better than typescript
const test2: [string[], number[]] = partition(['a', 2, 3, '3'], (x): x is string => {
return typeof x === 'string';
});
const test3: [number[], number[]] = partition([1, 2, 3, 4], x => typeof x == 'string');
const test4: [unknown[], unknown[]] = partition([], n => n > 3); // [[], []]
const test5: [boolean[], number[]] = partition([1, true, 2, 3, true], isBoolean);

// Not OK
// @ts-expect-error
Expand All @@ -19,3 +22,7 @@ partition(null, n => n > 1);
partition(undefined, n => n > 1);
// @ts-expect-error
partition([1, 5, 2, 4, 3], n => n > 3, "a");

function isBoolean(x: unknown): x is boolean {
return typeof x === 'boolean';
}
Loading