AI solution for TypeScript puzzle on BFE.dev
27. implement Flat<T>
Here's the solution to the TypeScript coding question:
type Flat<T extends unknown[]> = T extends [infer H, ...infer R] ? [...(H extends unknown[] ? Flat<H> : [H]), ...Flat<R>] : [];
Explanation:
We define the Flat type with a generic type parameter T that extends an array of unknown types (T extends unknown[]). We use conditional types to check if the array has at least one element (T extends [infer H, ...infer R]), and if so, we check if the first element H is itself an array (H extends unknown[]). If it is, we recursively apply the Flat type to the H element (Flat<H>), which will flatten any nested arrays. Otherwise, we wrap the non-array element in a new array ([H]). We then concatenate the flattened H element (as an array) with the result of recursively applying Flat to the rest of the array (...Flat<R>). If the input array is empty, we return an empty array ([]).
For example, the Flat<[1,[2,3], [4,[5,[6]]]]> type resolves as follows:
T=[1,[2,3], [4,[5,[6]]]]T extends [infer H, ...infer R]matches, settingH=1andR=[[2,3], [4,[5,[6]]]]H extends unknown[]does not match, so we wrapHin an array:[1]- Recursively flatten the rest of the input array:
Flat<[[2,3], [4,[5,[6]]]]> [[2,3], [4,[5,[6]]]]matchesT extends [infer H, ...infer R], settingH=[2,3]andR=[[4,[5,[6]]]]H extends unknown[]matches, so recursively applyFlattoH:Flat<[2,3]>, which resolves to[2,3]- Concatenate the flattened
Harray with the result of recursively flattening the rest of the input:[2,3, ...Flat<[[4,[5,[6]]]]>] [[4,[5,[6]]]]matchesT extends [infer H, ...infer R], settingH=[4, [5, [6]]]andR=[]H extends unknown[]matches, so recursively applyFlattoH:Flat<[4,[5,[6]]]>Flat<[4,[5,[6]]]>resolves to[4,5,6]- Concatenate the flattened
Harray with the result of recursively flattening the rest of the input:[2,3,4,5,6, ...Flat<[]>] Flat<[]>resolves to[]- Concatenate the flattened
Harray with the empty array:[2,3,4,5,6] - Concatenate the result with the flattened rest of the input:
[1,2,3,4,5,6] - The final result of
Flat<[1,[2,3], [4,[5,[6]]]]>is[1,2,3,4,5,6].