【问题标题】:Typescript Interface Definition dynamicTypescript 接口定义动态
【发布时间】:2020-11-24 07:09:45
【问题描述】:

我正在尝试为以下数据定义一个接口:

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

result 对象中的键和值是动态的。甚至对象数组中的值也是动态的,但格式为 string: number 或者该数组可以为空,就像在 data3 中一样。

我尝试使用[x:any]: any,但看起来它会消除接口中定义的其余类型的重要性,因为它会匹配任何东西。

有人可以帮我吗?

【问题讨论】:

    标签: javascript typescript ecmascript-6 typescript-typings typescript2.0


    【解决方案1】:

    您可以如下定义动态键接口:

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

    【讨论】:

    • 但是什么是childkey和key?
    • 这只是一个变量名,暗示打字稿密钥是动态的。你可以有任何你想要的名字。此外,由于 JavaScript 对象键是字符串,因此您将其指定为字符串。
    【解决方案2】:

    你可以做类似的事情 -->

    您不需要使用索引器(因为它的类型安全性稍差)。你有两个选择:

    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'] }
     ]
    

    我个人推荐选项 A(当您使用类而不是接口时迁移更简单)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-27
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-10
      相关资源
      最近更新 更多