2
votes

I've this below function to flatten an array item,

 private flatArray(data): [] {
    return data.reduce((accu, val) => (Array.isArray(val) ? accu.concat(this.flatArray(val)) : accu.concat(val)), []);
  }

Now I wanted to add types to the argument, Below is how I did it,

  private flatArray<T>(data: Array<Array<T>> | Array<T>): Array<T> 

But I get this error,

Cannot invoke an expression whose type lacks a call signature. Type '{ (callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; (callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; (callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;...' has no compatible call signatures.ts(2349)

Any idea how to fix this issue ?

1
There is .flat() though ...Jonas Wilms
I can use that, but it dosen't support IEuser007

1 Answers

2
votes

You probably want to do

private flatArray<T>(data: Array<T | Array<T>>): Array<T>

A more robust approach in order to allow recursively nested arrays would be using a dedicated readonly type.

interface NestedArray<T> extends ReadonlyArray<NestedArray<T> | T> { }

// ...

private flatArray<T>(data: NestedArray<T>): Array<T>

Playground link