[英]Typescript definition pattern for object with index
I have data that looks like this: 我有看起来像这样的数据:
let equipment:Equipment = {
"1": {
"name": "abc",
"data": 123
},
"2": {
"name": "def",
"data": 234
},
"3": {
"name": "ghi",
"data": 345
},
...
}
This would be easy to put in an array, but my equipment ID's start with 1 and I don't want to deal with the logic of excluding the [0] (which would be null) element. 这将很容易放入数组中,但是我的设备ID以1开头,我不想处理排除[0](将为空)元素的逻辑。
Given this, I have come up with the following TypeScript Declaration Files. 鉴于此,我提出了以下TypeScript声明文件。
interface Equipment
{
[ k: number ]: EquipmentBase;
}
interface EquipmentBase
{
name: string
data: number
}
Further, when I return this equipment object with others I need to put it in a JSON object which requires yet another interface declaration. 此外,当我将这个设备对象与其他对象一起返回时,我需要将其放入需要另一个接口声明的JSON对象中。
interface EquipmentObj
{
equipment: Equipment
}
/* returns {equipment:
{
"1": {
"name": "abc",
"data": 123
},
"2": {
"name": "def",
"data": 234
},
"3": {
"name": "ghi",
"data": 345
},
...
}
}
*/
This feels like an excessive number of declarations (Equipment, EquipmentObj) just to declare an object that holds data. 只是为了声明一个保存数据的对象,感觉就像是过多的声明(Equipment,EquipmentObj)。 Is there a different/better way to minimize the number of declarations that I am using?
是否有其他/更好的方法来最小化我使用的声明数量?
Well, you can do this: 好吧,你可以这样做:
interface EquipmentObj
{
equipment: {
[k: number]: {
name: string
data: number
}
}
}
But then, you can no longer declare anything as one of the inner types. 但是,您再也不能将任何内容声明为内部类型之一。
So if you need to type a variable, parameter, or return type as Equipment
or EquipmentBase
, then you could not fold that one in. 因此,如果您需要将变量,参数或返回类型键入为
Equipment
或EquipmentBase
,则无法将其折叠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.