0

This function declaration compiles and seems to be correct:

function flattenDeep<T>(arr: Array<any>): Array<T>{
  return Array.isArray(arr) ? arr.reduce( (a, b) => [...flattenDeep(a), ...flattenDeep(b)] , []) : [arr];
}

but this function expression doesn't compile:

 const flattenDeep<T> = (arr: Array<any>): Array<T> => {
   return Array.isArray(arr) ? arr.reduce( (a, b) => [...flattenDeep(a), ...flattenDeep(b)] , []) : [arr];
 };

I am looking for the right syntax to the same with a function expression if it's possible.

I am calling flattenDeep like so:

  enq(...args: Array<Array<X> | X>): Array<boolean> {
    return flattenDeep<X>(Array.from(arguments)).map(v => {
      return v['key'] ? this.enqueue(v.key, v.value) : this.enqueue(v.value);
    });
  }

I am not sure if what I have is sufficient to convey that flattenDeep should return type X.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

1 Answers1

1

I fiddled/futzed around some more and this seems to work:

const flattenDeep =  <T>(arr: Array<any>): Array<T> => {
  return Array.isArray(arr) ? arr.reduce( (a, b) => [...flattenDeep(a), ...flattenDeep(b)] , []) : [arr];
};
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817