I'm confused by nested array behavior in TypeScript. I want to use a single type for unknown-depth arrays.
Here is a mockup of my problem:
type PossiblyNested = Array<number> | Array<Array<number>>; // Limited to 2D, for simplicity. My actual input will 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); // Argument of type 'number' is not assignable to parameter of type 'number & number[]'.
// Type 'number' is not assignable to type 'number[]'.ts(2345)
}
for (let i = 0; i < NESTED_INPUTS.length; ++i) {
const RAW = NESTED_INPUTS.shift();
PROCESSED_INPUTS.push(RAW); // Argument of type 'number[]' is not assignable to parameter of type 'number & number[]'.
// Type 'number[]' is not assignable to type 'number'.ts(2345)
}
I have tried using generic templated types, and recursive types, to no avail. I might not understand those well enough.
I have been able to satisfy TS and Lint with 'any' and 'unknown', but that leads to other problems. I want to avoid those at all costs.
I have had success initializing PROCESSED_INPUTS with items of the expected format (see next example), but I then must manually empty it before the loop. It feels very clunky.
const PROCESSED_INPUTS_FLAT: PossiblyNested = [0]; // include content
PROCESSED_INPUTS_FLAT.pop(); // manually empty
for (let i = 0; i < FLAT_INPUTS.length; ++i) {
const RAW = FLAT_INPUTS.shift();
PROCESSED_INPUTS_FLAT.push(RAW); // TS and Lint are now happy
}
Is there a cleaner way to initialize PROCESSED_INPUTS so that it takes pushed entries dynamically, whether they are number or number[]? I hoped that's what I was setting up with my PossiblyNested type ... apparently not.
Thanks in advance for any help!