无限深度数组的打字稿类型

问题描述 投票:0回答:3

如何定义类型

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

打字稿?

编辑: 解决方案是:

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

但这是不允许的。

这是我的用例:

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);
}
typescript
3个回答
12
投票

与 Rodris 的答案不同,您不需要添加任何内置的数组属性,如地图、长度等。

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));

更重要的是,您可以使其通用以指定类型:

type RecursiveArray<T> = Array<T | RecursiveArray<T>>;

3
投票

您可以创建递归接口。

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";

1
投票

我刚刚遇到这个问题,没有找到任何类型定义的解决方案,所以我想出了这个类型(我对此感到非常自豪):

type NestedArray<T, Depth extends number = 1> = Depth extends 0 ? T : NestedArray<T[], [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10][Depth]>;

type string2D = NestedArray<string, 2>; //=> string[][]

type string3D = NestedArray<string, 3>; //=> string[][][]

这只适用于最多 10 级递归(查看

[-1, ..., 10]
数组,如果需要更多,只需扩展它)。我希望这会对未来的谷歌员工有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.