首页 > 解决方案 > 来自 _.mapKeys(items, 'id') 的对象的 typescript 接口

问题描述

我正在使用 react、Redux,并尝试在组件上使用 typescript。在 reducer 中,我使用 lodash mapKeys 将对象数组从以下位置展平:

 [  
   {id:1, blah blah}
   {id:2, blah blah}
 ]

to: 
 {
    "1", {id:1, blah blah},
    "2", {id:2, blah blah}
 }

这有助于减速器,因为我不玩数组游戏。

问题:如何在打字稿界面中定义该扁平对象?

更多细节......

我有一个Itodo的界面:

  export interface ITodo {
    id:number;
    subject:string;
    body:string;
    status: number;
    result:number;
  }

在我的 reducer 中,我使用 lodash mapKeys 来更改它,这样我就可以取回一系列属性,而不是数组,其中 id 作为属性名称。(见下文)

如何创建一个接口来为我的反应组件表达这一点?

  const response =
   [
     {
       "id": 1,
       "subject": "subject a",
       "body": "body a",
       "status": 0,
       "result": 0,
       "delete": null
     },
     {
       "id": 2,
       "subject": "subject b",
       "body": "body b",
       "status": 2,
       "result": 2,
       "delete": null
     },
     {
       "id": 3,
       "subject": "subject c",
       "body": "body c",
       "status": 2,
       "result": 2,
       "delete": null
     }
   ]

   const mapped = _.mapKeys(response,'id')

   console.log (JSON.stringify(mapped,null,2)
   {
     "1": {
       "id": 1,
       "subject": "subject a",
       "body": "body a",
       "status": 0,
       "result": 0,
       "delete": null
     },
     "2": {
       "id": 2,
       "subject": "subject b",
       "body": "body b",
       "status": 2,
       "result": 2,
       "delete": null
     },
     "3": {
       "id": 3,
       "subject": "subject c",
       "body": "body c",
       "status": 2,
       "result": 2,
       "delete": null
     }
   }

标签: typescript

解决方案


通常我会这样做:

export interface ITodo {
    id:number;
    subject:string;
    body:string;
    status: number;
    result:number;
  }

interface ITodoObject {
    [key: number]: ITodo
}

推荐阅读