-
Notifications
You must be signed in to change notification settings - Fork 57
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
type-challenges-solutions/en/medium-flatten #314
Comments
There are two issues with this solution: Given the following test case... // @ts-expect-error
type error = Flatten<undefined>
type Flatten<T extends unknown[]> =
T extends [infer H, ...infer Rest]
? H extends unknown[]
? [...Flatten<H>, ...Flatten<Rest>]
: [H, ...Flatten<Rest>]
: []
type Flatten<T extends any[]> = // T[0] cannot extend unknown
T extends [infer H, ...infer Rest]
? H extends unknown[]
? [...Flatten<T[0]>, ...Flatten<Rest>]
: [T[0], ...Flatten<Rest>]
: [] |
My solution is similar with @MajorLift one, except I'm using type Flatten<T extends unknown[]> = T extends [infer Head, ...infer Tail]
? Head extends unknown[]
? Flatten<[...Head, ...Tail]>
: [Head, ...Flatten<Tail>]
: []; |
@albert-luta Nice! It seems that your solution would result in less optimal recursion depth, as the |
I believe this initial example could be improved type Flatten<T> = T extends []
? []
: T extends [infer H, ...infer T]
? [H, T]
: [T];
|
My solution using acc to trace the result while in recursion
|
Flatten
This project is aimed at helping you better understand how the type system works, writing your own utilities, or just having fun with the challenges.
https://ghaiklor.github.io/type-challenges-solutions/en/medium-flatten.html
The text was updated successfully, but these errors were encountered: