This question is much more academic than practical.
I have a function filledArray(val, ...dims), which takes a fill value and a variable number of dimensions, and builds a nested multidimensional array filled with that value, to the specification in the dimensions. For example:
> filledArray('x', 5)
[ 'x', 'x', 'x', 'x', 'x' ]
> filledArray('x', 2, 5)
[ [ 'x', 'x', 'x', 'x', 'x' ],
[ 'x', 'x', 'x', 'x', 'x' ], ]
> filledArray('x', 2, 5, 1)
[ [ [ 'x' ], [ 'x' ], [ 'x' ], [ 'x' ], [ 'x' ] ],
[ [ 'x' ], [ 'x' ], [ 'x' ], [ 'x' ], [ 'x' ] ] ]
Typescript infers that the return type of this function is any. Can the true return type be expressed in the type system somehow, so that the three return values above are correctly typed as string[], string[][], and string[][][]? (And so on, for deeper and deeper arrays?)
A sample implementation of this function:
function filledArray<T>(val: T, ...dims: number[]) {
if (dims.length == 0)
return val
let [dim, ...rest] = dims
return Array.from(Array(dim), _ => filledArray(val, ...rest))
}
Interestingly, it even seems like specifying a fixed number of overload declarations seems to make the final ...rest in the function somehow be of the wrong type...