9

Say I have an array of strings like:

const a = ['foo', ['aa'], [['zzz',['bar']]]];
    
export const acceptsArray = (v: Array<any>) : string => {
   returns flattenDeep(v).join(' ');
};

besides using Array<any> how can I represent a nested array of strings?

2 Answers 2

15

SOLUTION

Note only works on Typescript version 3.7+

type A = 'foo' | 'aa' | 'zzz' | 'bar' | A[]

const a:A = ['foo', ['aa'], [['zzz',['bar']]]];

export const acceptsArray = (v: Array<A>) : string => {
   returns flattenDeep(v).join(' ');
};

Thank you

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

2 Comments

does this go two levels deep? I am looking to represent an arbitrary level of nesting
yes it goes arbitrary level deep.
7

Please check this utility function I wrote earlier.

// NestedArray<T> represents T or Array of T or Array of Array of T .....
// let nestedNumbers: NestedArray<number> = [[[[[1]]]]];
export type NestedArray<T> = Array<T> | Array<NestedArray<T>>;

// Able to flatten deeply nested array
// flattenArray(nestedNumbers) should produce => [1] : Array<number>
export const flattenArray = <T>(arr: NestedArray<T>): Array<T> => {
  if (!Array.isArray(arr)) return arr ? [arr] : [];

  return arr.reduce<Array<T>>((acc: Array<T>, item: NestedArray<T>) => {
    if (Array.isArray(item)) {
      return [...acc, ...flattenArray(item)];
    }
    return [...acc, item];
  }, []);
}

1 Comment

if it's always an array, seems like this would be more accurate? export type NestedArray<T> = Array<T> | Array<NestedArray<T>>;, since T itself doesn't have to be an array here.

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.