简体   繁体   English

如何在TypeScrypt中使用C#中的元组列表

[英]How to use List of tuples from C# in TypeScrypt

I want to get list of tuples from server and use them in TypeScript on client. 我想从服务器获取元组列表,并在客户端的TypeScript中使用它们。

Problem is that I don't know how to declare list of tuples in TypeScript? 问题是我不知道如何在TypeScript中声明元组列表? Message property on client is null even when should not be. 客户端上的Message属性为null,即使不应设置为null。

This are list of tuples in entity on server 这是服务器上实体中的元组列表

public IEnumerable<Tuple<string, string>> Messages { get; set; }

Return List of entities in Json (there are more properties but to simplify): 返回Json中实体的列表(有更多属性,但为了简化):

[  
   {  
      "id":93,
      "messages":[  
         {  
            "item1":"A1",
            "item2":"Hello"
         },
         {  
            "item1":"A2",
            "item2":"World"
         }
      ]
   },
   {  
      "id":94,
      "messages":null
   }
]

I try to create same property in TypeScript like this: 我尝试像这样在TypeScript中创建相同的属性:

messages: { item1: string, item2: string }[];

All other properites are fine, problem is only with messages. 所有其他属性都很好,问题仅在于消息。

Your type should work. 您的类型应该起作用。 With the sample data, this has the expected output: 对于样本数据,它具有预期的输出:

interface Item {
    id: number;
    messages: {
        item1: string;
        item2: string;
    }[];
}

let typed: Item[] = json;
for (const item of typed) {
    console.log(item.id);
    if(!item.messages) continue;
    for(const message of item.messages){
        console.log(`${message.item1} - ${message.item2}`)
    }   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM