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.
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).
Launch price: $19 $29
One-time payment. Lifetime access to all pro challenges.
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:
ToUnion<T> helper normalizes the exclusion parameter: if T is an array, it converts it to a union via T[number]; otherwise it returns T as-isExcluded default parameter calls ToUnion<U> once upfront, avoiding redundant computation on each recursive stepWithout<T, U, Excluded> type recursively destructures the input tuple using T extends [infer First, ...infer Rest]First extends Excluded (meaning it should be removed), the element is skipped and recursion continues with Without<Rest, U, Excluded>[First, ...Without<Rest, U, Excluded>][] is returned as the base caseThis 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.
Get the latest TypeScript tips, tutorials, and updates delivered straight to your inbox.