I am facing some challenges with nested array behavior in TypeScript. I am looking for a way to define a single type that can handle arrays of unknown depth.
Let me illustrate my issue:
type PossiblyNested = Array<number> | Array<Array<number>>; // To keep it simple, let's limit it to 2D. In reality, my input could be up to 6-dimensional.
const FLAT_INPUTS: PossiblyNested = [0, 1];
const NESTED_INPUTS: PossiblyNested = [[0], [1]];
const PROCESSED_INPUTS: PossiblyNested = [];
for (let i = 0; i < FLAT_INPUTS.length; ++i) {
const RAW = FLAT_INPUTS.shift();
PROCESSED_INPUTS.push(RAW); // Error: Argument of type 'number' is not assignable to parameter of type 'number & number[]'.
}
for (let i = 0; i < NESTED_INPUTS.length; ++i) {
const RAW = NESTED_INPUTS.shift();
PROCESSED_INPUTS.push(RAW); // Error: Argument of type 'number[]' is not assignable to parameter of type 'number & number[]'.
}
I have experimented with generic templated types and recursive types, but without success. It seems like I need a clearer understanding of these concepts.
While using 'any' and 'unknown' satisfies TS and Lint, it poses other issues that I want to avoid at all costs.
Although initializing PROCESSED_INPUTS with the expected format works, having to empty it manually before the loop feels cumbersome.
const PROCESSED_INPUTS_FLAT: PossiblyNested = [0]; // include content
PROCESSED_INPUTS_FLAT.pop(); // manual emptying
for (let i = 0; i < FLAT_INPUTS.length; ++i) {
const RAW = FLAT_INPUTS.shift();
PROCESSED_INPUTS_FLAT.push(RAW); // TS and Lint are happy now
}
Is there a more elegant way to initialize PROCESSED_INPUTS so it can accept dynamically pushed entries, whether they are numbers or arrays of numbers? I thought that was the purpose of my PossiblyNested type... apparently not.
Thank you in advance for any assistance!