【问题标题】:How to use List of tuples from C# in TypeScrypt如何在 TypeScript 中使用 C# 中的元组列表
【发布时间】:2018-07-15 02:14:34
【问题描述】:

我想从服务器获取元组列表并在客户端的 TypeScript 中使用它们。

问题是我不知道如何在 TypeScript 中声明元组列表? 客户端上的消息属性即使不应该是 null。

这是服务器上实体中的元组列表

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

返回 Json 中的实体列表(还有更多属性但要简化):

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

我尝试像这样在 TypeScript 中创建相同的属性:

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

所有其他属性都很好,问题只是消息。

【问题讨论】:

  • 您能发布 JSON 的完整类型吗?不仅仅是messages。特别是什么不好。它应该工作
  • @Paritosh 这是您可以随时做的事情,但您应该始终避免

标签: c# json typescript


【解决方案1】:

您的类型应该可以工作。使用示例数据,这具有预期的输出:

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}`)
    }   
}

【讨论】:

  • 感谢您的帮助。
猜你喜欢
  • 2017-05-15
  • 2020-11-28
  • 2015-08-29
  • 1970-01-01
  • 2016-07-03
  • 2022-01-22
  • 1970-01-01
  • 2017-05-30
  • 1970-01-01
相关资源
最近更新 更多