C#的List<KeyValuePair<string,string>>在TypeScript中的等效类型及取值方法
回答
一、TypeScript中的等效类型定义
TypeScript没有和C# List<KeyValuePair<string, string>>完全对应的内置类型,但可以通过两种简洁方式实现等效映射:
- 独立键值对接口+数组
先定义单个键值对的结构,再用数组包裹作为metaData的类型:
interface KeyValuePair { key: string; value: string; } interface APIResponse { id: bigint; success: boolean; metaData: KeyValuePair[]; }
- 内联数组类型
如果不需要复用键值对结构,可直接在接口内联定义数组类型:
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
相关产品推荐
相关产品推荐

