DEV Community

Discussion on: Advanced TypeScript Exercises - Answer 6

Collapse
 
jopie64 profile image
Johan • Edited

So I tried in TypeScript Playground and the following seems also a valid solution for the naive problem:


type NaiveFlat<T extends any[]> = T[number] extends any[] ? T[number][number] : T[number]

But this approach doesn't seem to work for DeepFlat


type DeepFlat<T extends any[]> = T[number] extends any[] ? DeepFlat<T[number]> : T[number]

It screems about that it circularly references itself. But doesn't it do that in your approach too? Why is it not an error in your case?

Collapse
 
macsikora profile image
Pragmatic Maciej

Hi, thanks for the comment.
In order to avoid this message we can make a trick, and the trick is to exactly use mapped type. Pay attention that I can take your code and put into mapped type and it doesn't complain anymore:

type DeepFlat<T extends any[]> = {
  [K in keyof T] : T[number] extends any[] ? DeepFlat<T[number]> : T[number]
}[0] // 0 means we now that it will be evaluated for the first item also fully