3

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.

Test0n3
  • 33
  • 1
  • 5

1 Answers1

1

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.

casieber
  • 7,264
  • 2
  • 20
  • 34
  • Thanks for your reply. Your method works for most cases, except the last one which includes {}. Had to add {} in the type. accum can be defines with T[] but val can't, not even MaybeArray[]. – Test0n3 Sep 19 '18 at 19:52