#459Medium

Flatten

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.

Challenge Instructions: Flatten

Medium

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).

Loading...

Detailed Explanation

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:

This 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.

Share this challenge

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount