#5117Medium

Without

Implement the type version of Lodash.without, Without<T, U> takes an Array T, number or array U and returns an Array without the elements of U. Learn union type manipulation, array type operations in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement a type-level version of Lodash's without function that filters elements from a tuple, removing any that appear in a given exclusion list.

Challenge Instructions: Without

Medium

Implement the type version of Lodash.without, Without<T, U> takes an Array T, number or array U and returns an Array without the elements of U.

type Res = Without<[1, 2], 1>; // expected to be [2]
type Res1 = Without<[1, 2, 4, 1, 5], [1, 2]>; // expected to be [4, 5]
type Res2 = Without<[2, 3, 2, 3, 2, 3, 2, 3], [2, 3]>; // expected to be []

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

ChallengeSolution
type cases = [
  Expect<Equal<Without<[1, 2], 1>, [2]>>,
  Expect<Equal<Without<[1, 2, 4, 1, 5], [1, 2]>, [4, 5]>>,
  Expect<Equal<Without<[2, 3, 2, 3, 2, 3, 2, 3], [2, 3]>, []>>,
]

Pro Challenge

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

One-time payment. Lifetime access.

Detailed Explanation

type ToUnion<T> = T extends any[] ? T[number] : T;
 
type Without<T extends any[], U, Excluded = ToUnion<U>> =
  T extends [infer First, ...infer Rest]
    ? First extends Excluded
      ? Without<Rest, U, Excluded>
      : [First, ...Without<Rest, U, Excluded>]
    : [];

How it works:

This challenge helps you understand union type normalization and recursive tuple filtering, and how to apply these concepts in real-world scenarios.

This challenge is originally from here.

Share this challenge

Learn the Concepts