'Unwrapping array types recursively in TypeScript

I need to create a function that can get a very "dynamic" parameter. it should be a ble to accept many types of arrays

class NdArray<T> {

}

// need to be able to get

f(number[]) // -> NdArray<number>
f(number[][]) // -> NdArray<number>
f(number[][][]) // -> NdArray<number>
//and so on...
f(string[]) // -> NdArray<string>
f(string[][]) // -> NdArray<string>
f(string[][][]) // -> NdArray<string>
// and generally
f(object[][][]...) // -> NdArray<object>


Solution 1:[1]

Recursively unwrap the array:

type UnwrapArray<A> = A extends unknown[] ? UnwrapArray<A[number]> : A;

If A is an array, we unwrap the type of its elements. Otherwise it's just something else we don't need to unwrap.

Your function f here could be something like:

function f<T>(type: T): NdArray<UnwrapArray<T>> {
    // a very cool implementation
}

Playground

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hittingonme