Yuzhe's Blog

yuzhes

Filter

Filter

Problem Link

Problem

Implement the type Filter<T, Predicate> which filters out elements from a tuple T that do not satisfy the Predicate type.

type Filtered = Filter<[1, 2, 3, 'a', 'b', 1], number> // [1, 2, 3, 1]

Solution

type Filter<T extends any[], P> =
  T extends [infer First, ...infer Rest]
    ? First extends P
      ? [First, ...Filter<Rest, P>]
      : Filter<Rest, P>
    : []

How it works:

  1. Recursively destructure the tuple into First and Rest.
  2. If First extends P, keep it in the output tuple.
  3. Otherwise, skip it and continue with Rest.
  4. Base case: empty tuple returns [].

Key Takeaways