TypeScript

partition — Split by Predicate

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Split an array into [pass, fail] in a single pass. Type guard overload lets the truthy bucket get a narrowed type when you pass a `x is T` predicate.
TypeScript
Raw
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
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.