typescript - 来自 _.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
}
}
解决方案
通常我会这样做:
export interface ITodo {
id:number;
subject:string;
body:string;
status: number;
result:number;
}
interface ITodoObject {
[key: number]: ITodo
}
推荐阅读
- python - 列表中的两个以下元素
- css - 如何将此样式应用于我的幻灯片?
- python - 将列与整数和字符串相乘
- visual-studio - Visual Studio 2017 V15.9.4 - CSharpRenameTrackingCodeFixProvider 遇到错误并已被禁用
- architecture - (Nand2tetris CPU)(什么/多少)在每个时钟周期发生?
- facebook - 如何确定用户使用哪个提供商登录
- sql - 文本解析的优化——Oracle SQL
- pytest - 将带有排除标签的测试报告为已跳过
- asp.net-core - 无法引用 Blazor 组件库项目
- laravel - 在比较表中使用 Goutte 截取亚马逊详细信息页面