【问题标题】:Typescript how to define array type with nested and predict打字稿如何用嵌套和预测定义数组类型
【发布时间】:2021-01-28 22:41:29
【问题描述】:

如何设置数组的类型

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

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

【问题讨论】:

    标签: javascript typescript types


    【解决方案1】:

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

    这行得通:

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

    或者,更直接地为你解答:

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

    然后只需使用 NestedStringArray 键入您的数组

    【讨论】:

    • 我在你的链接上发现了几乎相同的东西。类型 NestedArray = string | [字符串,...NestedArray[]];它的工作。谢谢
    猜你喜欢
    • 2019-08-03
    • 2017-04-13
    • 2022-10-14
    • 1970-01-01
    • 2023-01-05
    • 1970-01-01
    • 2020-10-20
    • 2019-02-10
    • 2019-04-24
    相关资源
    最近更新 更多