export function partition<T, S extends T>(
items: readonly T[], pred: (x: T) => x is S
): [S[], Exclude<T, S>[]];
export function partition<T>(
items: readonly T[], pred: (x: T) => boolean
): [T[], T[]];
export function partition<T>(items: readonly T[], pred: (x: T) => boolean): [T[], T[]] {
const pass: T[] = [], fail: T[] = [];
for (const x of items) (pred(x) ? pass : fail).push(x);
return [pass, fail];
}
const isString = (x: unknown): x is string => typeof x === 'string';
const [strs, others] = partition([1, 'a', 2, 'b', null], isString);
// strs: string[]
// others: (number | null)[] ← narrowed via the type guard
Create a free account and build your private vault. Share publicly whenever you want.