Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Proper way for multidimensional array argument

I'm working some JS algorithms with TS. So I made this functions:

function steamrollArray(arr: any[]): any[] {
  return arr.reduce(
    (accum: any, val: any) =>
      Array.isArray(val) ? accum.concat(steamrollArray(val)) : accum.concat(val)
  , []);
}

but the arguments need the flexibility to accept multiple dimension arrays, as follow:

steamrollArray([[["a"]], [["b"]]]);
steamrollArray([1, [2], [3, [[4]]]]);
steamrollArray([1, [], [3, [[4]]]]);
steamrollArray([1, {}, [3, [[4]]]]);

Which is the proper way to define the arguments for the function?

Certainly I could use Types, like here: typescript multidimensional array with different types but won't work with all cases.

like image 913
Test0n3 Avatar asked Dec 06 '25 04:12

Test0n3


1 Answers

You'll want to define a type that is possibly an array and possibly not. Something like:

type MaybeArray<T> = T | T[];

Then you can update your function to:

function steamrollArray<T>(arr: MaybeArray<T>[]): T[] {
    return arr.reduce(
        (accum: any, val: any) =>
             Array.isArray(val) ? accum.concat(steamrollArray(val)) : accum.concat(val)
    , []);
}

With that, Typescript will be able to parse the types correctly and understand your intent.

like image 164
casieber Avatar answered Dec 09 '25 18:12

casieber