#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:

[object Object]

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

ChallengeSolution
/* _____________ 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'>

Pro Challenge

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

One-time payment. Lifetime access.

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