Test0n3
Test0n3

Reputation: 33

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.

Upvotes: 3

Views: 1076

Answers (1)

casieber
casieber

Reputation: 7542

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.

Upvotes: 1

Related Questions