如何在TypeScript中为含动态键的数组定义接口?
问题分析与解决方案
首先你提供的JSON存在语法错误:数组[]内部不能使用键值对(如"userId1": {...}),这种键值对结构属于对象{}。正确的JSON结构应该是:
{ "userId1": { "flight_number": "aaa", "airport_iata": "AAA" }, "userId2": { "flight_number": "bbb", "airport_iata": "BBB" } }
情况1:使用对象结构(符合修正后的JSON)
你原本写的ResourceAllocationMessage接口完全匹配这个对象结构,直接使用即可:
interface ResourceAllocation { flight_number: string airport_iata: string } interface ResourceAllocationMessage { [userId: string]: ResourceAllocation } // 使用示例 const data: ResourceAllocationMessage = { userId1: { flight_number: "aaa", airport_iata: "AAA" }, userId2: { flight_number: "bbb", airport_iata: "BBB" } };
情况2:确实需要数组结构(如果实际数据是数组形式)
如果你的数据必须是数组结构,需要调整数据格式为每个元素包含userId和资源信息的结构,比如:
[ { "userId": "userId1", "flight_number": "aaa", "airport_iata": "AAA" }, { "userId": "userId2", "flight_number": "bbb", "airport_iata": "BBB" } ]
对应的TypeScript接口定义如下:
interface ResourceAllocationItem { userId: string flight_number: string airport_iata: string } // 数组类型直接用 ResourceAllocationItem[] const data: ResourceAllocationItem[] = [ { userId: "userId1", flight_number: "aaa", airport_iata: "AAA" }, { userId: "userId2", flight_number: "bbb", airport_iata: "BBB" } ];
内容的提问来源于stack exchange,提问作者Raphael Pinel
相关产品推荐
相关产品推荐

