DEV Community

Discussion on: Advanced TypeScript Exercises - Question 6

kashyaprahul94 profile image
Rahul Kashyap • Edited on

This time, after a lot of thought & attempts :P

Naive version -

// Basic level 1 values of a type
type Level1<T extends any[]> = T[number];

// Level 2 making use of level 1 twice
type Level2<T extends any[]> = Level1<Level1<T>>;

type NaiveFlat<T extends any[]> = Level2<T>;

type Naive = [['a'], ['b', 'c'], ['d']];
type NaiveTestResult = Assert<NaiveFlat<Naive>, "a" | "b" | "c" | "d">; // should be true

Deep version-

// Recursive mapped type for nested level
type NestedLevel<T extends any[]> = {
  [K in keyof T]: T[K] extends any[] ? NestedLevel<T[K]> : T[K];

type DeepFlat<T extends any[]> = NestedLevel<T>;

type Deep = [['a'], ['b', 'c'], [['d']], [[[['e']]]]];
type DeepTestResult = Assert<DeepFlat<Deep>, "a" | "b" | "c" | "d" | "e"> // should be true

Playground link

macsikora profile image
Pragmatic Maciej Author • Edited on

Nice but the solution can be simpler 😉

kashyaprahul94 profile image
Rahul Kashyap

Yeah, realised it later. Updated the answer :)