You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#的List<KeyValuePair<string,string>>在TypeScript中的等效类型及取值方法

回答

一、TypeScript中的等效类型定义

TypeScript没有和C# List<KeyValuePair<string, string>>完全对应的内置类型,但可以通过两种简洁方式实现等效映射:

  1. 独立键值对接口+数组
    先定义单个键值对的结构,再用数组包裹作为metaData的类型:
interface KeyValuePair {
  key: string;
  value: string;
}

interface APIResponse {
  id: bigint;
  success: boolean;
  metaData: KeyValuePair[];
}
  1. 内联数组类型
    如果不需要复用键值对结构,可直接在接口内联定义数组类型:
interface APIResponse {
  id: bigint;
  success: boolean;
  metaData: Array<{ key: string; value: string }>;
}

二、获取指定key的value值

利用数组的find方法快速定位目标键值对,再提取对应value:

// 假设response是已获取的APIResponse类型数据
const nameValue = response.metaData.find(item => item.key === 'Name')?.value;
  • find会返回第一个匹配key === 'Name'的元素,无匹配项时返回undefined
  • 可选链?.能避免因找不到元素而触发的Cannot read property 'value' of undefined错误

如果API返回的metaData中可能存在多个相同key的项,可用filter配合map提取所有对应value:

const nameValues = response.metaData
  .filter(item => item.key === 'Name')
  .map(item => item.value);

内容的提问来源于stack exchange,提问作者AlpUygur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 13:43:37