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:
[object Object]Change the following code to make the test cases pass (no type check errors).
/* _____________ Your Code Here _____________ */
type Flatten = any
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '../helpers'
type cases = [
Expect<Equal<Flatten<[]>, []>>,
Expect<Equal<Flatten<[1, 2, 3, 4]>, [1, 2, 3, 4]>>,
Expect<Equal<Flatten<[1, [2]]>, [1, 2]>>,
Expect<Equal<Flatten<[1, 2, [3, 4], [[[5]]]]>, [1, 2, 3, 4, 5]>>,
Expect<
Equal<
Flatten<[{ foo: 'bar'; 2: 10 }, 'foobar']>,
[{ foo: 'bar'; 2: 10 }, 'foobar']
>
>,
]
// @ts-expect-error
type error = Flatten<'1'>
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
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.