打字稿如何使用嵌套和预测定义数组类型

时间:2021-01-28 22:41:29

标签: javascript typescript types

如何为数组设置类型

["string", ["string", ["other string"],["any"]], ["string", ["string", ["something string"]]], .... ]

也就是说,深度可以是任意的。 索引 '0' 之后的数组数也是。 主要条件,索引'0'下的类型必须是'string'。

1 个答案:

答案 0 :(得分:0)

来自 https://stackoverflow.com/a/60722301/11745228 的 Ulad Kasach,

这有效:

type ValueOrArray<T> = T | ValueOrArray<T>[];
type NestedStringArray = ValueOrArray<string>;

或者,更直接地回答您的问题:

type StringOrArray = string | StringOrArray[];
type NestedArray = StringOrArray;

然后只需使用 NestedStringArray

键入您的数组