Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript type for array with infinite depth

Tags:

typescript

How do I define a type for

string|string[]|string[][]|string[][][] // ad infinitum

in typescript?

edit: the solution would be:

type Rec = string | string[] | Rec[]

but that is not allowed.

Here is my usecase:

interface RecursiveArray<T> {
    [index: number]: (RecursiveArray<T> | T);
}

type Recursive<T> = T|RecursiveArray<T>

function stringValue (value: Recursive<string|boolean>): Recursive<string> {
  if (typeof value === 'boolean') {
    return value ? 'true' : 'false';
  }
  if (Array.isArray (value)) {
    return (value).map (stringValue);
  }
  return stringValue(value);
}
like image 590
Galdor Avatar asked Jun 23 '17 06:06

Galdor


2 Answers

Unlike the answer by Rodris you won't need to add any of the built in Array properties like map, length, etc.

type RecursiveArray = Array<RecursiveArray | string>;

let arr: RecursiveArray = [];
arr[1] = [];
arr[1][2] = [];
arr[1][2][2] = "item 122";

// In the other answer this throws a type error
arr[1][2][3] = ['1', '2', '3'];
arr[1][2][3].forEach(item => console.log(item));

like image 163
Alexis Tyler Avatar answered Sep 24 '22 01:09

Alexis Tyler


You can create a recursive interface.

interface RecursiveArray {
    [index: number]: (RecursiveArray | string);
    length: number;
}

let arr: RecursiveArray = [];
arr[1] = [];
arr[1][2] = [];
arr[1][2][2] = "item 122";
arr[1][2][3] = "item 123";
like image 34
Rodris Avatar answered Sep 22 '22 01:09

Rodris