Filter
Filter
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:
- Recursively destructure the tuple into
FirstandRest. - If
First extends P, keep it in the output tuple. - Otherwise, skip it and continue with
Rest. - Base case: empty tuple returns
[].
Key Takeaways
- The standard “recursive tuple filter” pattern in TypeScript type-land mirrors
Array.prototype.filterat the type level. First extends Pis a subtype check — it keeps elements that are assignable toP.- Building the result with
[First, ...Filter<Rest, P>]preserves tuple structure and element types.