简体   繁体   English

Typescript 接口定义动态

[英]Typescript Interface Definition dynamic

I am trying to define an interface for the following data:我正在尝试为以下数据定义一个接口:

result =
{
   "data1" : [ { "type1" : 30 }, { "type2" :40 } ],
   "data1" : [ { "abc" : 40 }, { "def" 940 } ],
   "data3" : []
}

here the keys and values inside result object are dynamic.这里result object 中的键和值是动态的。 Even the values inside array of objects are dynamic but it will be of format string: number or that array can be empty just as in data3 .即使对象数组中的值也是动态的,但它将是格式string: number ,或者该数组可以为空,就像在data3中一样。

I tried using [x:any]: any , but looks like it will remove the significance of rest of the types defined in interface as it will match eveything.我尝试使用[x:any]: any ,但看起来它将消除接口中定义的类型的 rest 的重要性,因为它将匹配所有内容。

Can someone help me here?有人可以帮我吗?

You can define dynamic key interface as follows:您可以按如下方式定义动态按键接口:

interface Result {
  [key: string]: {
    [childKey: string]: number;
  }[];
}

Something similar you can do -->您可以做类似的事情 -->

You don't need to use an indexer (since it a bit less typesafe).您不需要使用索引器(因为它的类型安全性较低)。 You have two options:你有两个选择:

interface EnumServiceItem {
   id: int; label: string; key: any
}

interface EnumServiceItems extends Array<EnumServiceItem>{}


// Option A 
var result: EnumServiceItem[] = [
 { id: 0, label: 'CId', key: 'contentId' },
 { id: 1, label: 'Modified By', key: 'modifiedBy' },
 { id: 2, label: 'Modified Date', key: 'modified' },
 { id: 3, label: 'Status', key: 'contentStatusId' },
 { id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
 { id: 5, label: 'Title', key: 'title' },
 { id: 6, label: 'Type', key: 'contentTypeId' },
 { id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
];


// Option B
var result: EnumServiceItems = [
 { id: 0, label: 'CId', key: 'contentId' },
 { id: 1, label: 'Modified By', key: 'modifiedBy' },
 { id: 2, label: 'Modified Date', key: 'modified' },
 { id: 3, label: 'Status', key: 'contentStatusId' },
 { id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
 { id: 5, label: 'Title', key: 'title' },
 { id: 6, label: 'Type', key: 'contentTypeId' },
 { id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
 ]

Personally I recommend Option A (simpler migration when you are using classes not interfaces).我个人推荐选项 A(当您使用类而不是接口时迁移更简单)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM