【发布时间】:2021-08-28 17:50:45
【问题描述】:
我有两个非常相似的模型对象(Angular 12 前端):
export interface UserGet {
id: string;
firstName: string;
lastName: string;
hobby: Hobby;
}
export interface UserPost {
firstName: string;
lastName: string;
hobby: number;
}
export interface Hobby {
id: string;
hobby: string;
}
我想将 UserGet 对象映射到 UserPost 对象。
当前使用给定 userGet-object 的方法:
const userPost: userPost = {
firstName: this.userGet.firstName,
lastName: this.userGet.lastName,
hobby: this.userGet.hobby.id;
}
看起来很简单,但实际上,我有更多的字段,我需要用相同的方法映射更多的对象。
是否有更短/更优雅的 ES6 打字稿解决方案来映射模型,类似于我的示例,具有以下结构:
- 目标对象中可能缺少某些字段
- 目标对象中的某些字段可能属于不同类型
提前致谢
【问题讨论】:
-
那么,您正在寻找类似
Automapper但用于 javascript/typescript? -
你为什么要这个?如果合同相同,为什么不为两者都设置一个对象?有 2 个基于 http 操作的合同是没有意义的,特别是如果您正在修改相同的资源。
-
@Bargros:模型设计正是我在其他帖子中所要求的。我听说 GET 字段类型不能与 POST 完全相同,只是因为它是同一个实体。因此合同不一样。如果您对此有其他意见,请在stackoverflow.com/questions/67940442 发表评论
-
我已经在你的其他帖子中回复了。
标签: angular typescript ecmascript-6 ecmascript-5