【问题标题】:How to create an array with a specific type at a specified index?如何在指定索引处创建具有特定类型的数组?
【发布时间】:2019-07-20 02:30:27
【问题描述】:
type MyArray<T> = [data: T[] , count: number ]; // doesn't work

在客户端,我想使用 MyArray 类型来映射来自 API 的数据并能够调用其“数据”或“计数”属性。 API 以数组的形式传递数据,数组在索引 0 处有数据,在索引 1 处有一个数字。

【问题讨论】:

  • 所以你有两种类型,一种是type MyArray&lt;T&gt; = [T[], number],另一种是type MyData&lt;T&gt; = {data: T[], count: number}。我认为将其表达为单一类型是没有意义的......你真的想要一个接受 MyArray&lt;T&gt; 并返回 MyData&lt;T&gt; 的函数。

标签: arrays typescript types


【解决方案1】:

您正在寻找tuple type:

type MyArray<T> = [T[], number];

元组成员不能有名称,它们只是位置性的,并且在运行时使用数组重新发送

使用示例:

type MyArray<T> = [T[], number];
let data : MyArray<string> = [["data1", "data2"], 2]
let arr = data[0] // string[]
let count  = data[1] // number

【讨论】:

    猜你喜欢
    • 2021-06-16
    • 2015-11-23
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    • 2015-09-14
    • 1970-01-01
    • 2015-07-21
    相关资源
    最近更新 更多