DEV Community

Discussion on: Advanced TypeScript Exercises - Question 6

Collapse
avfirsov profile image
Andrew Firsov • Edited on

Deep Version -- Hard way:

type OmitFirstValue<T extends unknown[]> = ((...args: T) => void) extends (x: any, ...rest: infer R) => void
  ? R
  : never;

type Prepend<T extends unknown[], V> = ((x: V, ...args: T) => void) extends (...result: infer R) => void ? R : never;

// Question 6.2
type DeepFlat<T extends any[]> = {
  true: T[0] extends any[] ? DeepFlat<T[0]> : T[0];
  false: Prepend<[DeepFlat<OmitFirstValue<T>>], T[0] extends any[] ? DeepFlat<T[0]> : T[0]>[number];
}[T['length'] extends 1 ? 'true' : 'false']
Enter fullscreen mode Exit fullscreen mode

Deep version -- easy way:

type DeepFlat<T extends any[]> = {
  [K in keyof T]: T[K] extends any[] ? DeepFlat<T[K]> : T[K];
}[number]
Enter fullscreen mode Exit fullscreen mode