In this challenge, you would need to write a type that takes an array and emitted the flatten array type. Learn array type operations in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll write a type that takes a nested array and produces a fully flattened array type, recursively unwrapping all levels of nesting.
In this challenge, you would need to write a type that takes an array and emitted the flatten array type.
For example:
type flatten = Flatten<[1, 2, [3, 4], [[[5]]]]> // [1, 2, 3, 4, 5]Change the following code to make the test cases pass (no type check errors).
We recursively process each element of the tuple. If an element is itself an array, we flatten it first and spread the result, then continue with the rest.
type Flatten<T extends any[]> = T extends [infer First, ...infer Rest]
? First extends any[]
? [...Flatten<First>, ...Flatten<Rest>]
: [First, ...Flatten<Rest>]
: []How it works:
T extends [infer First, ...infer Rest] destructures the tuple into the first element and the remaining elementsFirst extends any[] checks whether the first element is itself an arrayFirst is an array, we recursively flatten it with Flatten<First> and spread the result, then concatenate with the recursively flattened RestFirst is not an array, we keep it as-is and continue flattening RestThis challenge helps you understand recursive type flattening with conditional array detection and how to apply this concept in real-world scenarios.
This challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount