#18220Medium

Filter

Implement the type `Filter<T, Predicate>` takes an Array `T`, primitive type or union primitive type `Predicate` and returns an Array include the elements of `Predicate`. Learn array type operations in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement Filter<T, Predicate> which takes a tuple T and a primitive type (or union of primitive types) Predicate, and returns a new tuple containing only the elements that extend Predicate.

Challenge Instructions: Filter

Medium

Implement the type Filter<T, Predicate> takes an Array T, primitive type or union primitive type Predicate and returns an Array include the elements of Predicate.

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
type Falsy = false | 0 | '' | null | undefined

type cases = [
  Expect<Equal<Filter<[0, 1, 2], 2>, [2]>>,
  Expect<Equal<Filter<[0, 1, 2], 0 | 1>, [0, 1]>>,
  Expect<Equal<Filter<[0, 1, 2], Falsy>, [0]>>,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

We recursively walk through the tuple, checking each element against the predicate and accumulating matches.

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:

This challenge helps you understand recursive tuple filtering with conditional types and how to apply this concept in real-world scenarios.

This challenge is originally from here.

Share this challenge

Learn the Concepts