2

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 ?

2
  • 2
    There is .flat() though ... Commented Jul 30, 2019 at 9:46
  • I can use that, but it dosen't support IE Commented Jul 30, 2019 at 10:01

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

8 Comments

Is there a way to do that without narrowing an array type to readonly?
You mean NestedArray<T> extends Array<NestedArray<T> | T>? Yes, that restricts the function to only accepting writable arrays.
Are you sure that this solves the problem described by the OP? Cause I don't see any difference between Array<T> | Array<Array<T>> and Array<Array<T> | T>
@JonasWilms one is array of T OR array of arrays of T; the other is Array whose elements can be either T or arrays of T simultaneously.
@zerkms sure, but the OP might wants the first. Not sure how this addresses the question. Also not sure how this is related to the data.reduce(...) type missmatch.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.