如何用Automapper TypeScript映射Map/Record类型的复杂对象?
automapper-ts 处理复杂类型(Map/Record)时的问题
我正在使用 automapper-ts 搭配 ttypescript 插件自动生成映射,简单对象处理正常,但遇到Record<string, any>或Map<string, AnotherObject>这类复杂类型时出现以下问题:
1. Map<string, SampleItem> 类型映射异常
代码示例
export class SampleItem { type: string; name: string; example?: unknown; constructor(data?: SampleItem) { Object.assign(this, data); } } class Entity { @AutoMap(() => SampleItem) sample: Map<string, SampleItem>; @AutoMap(() => Object) details: Record<string, any>; }
测试场景与差异
测试时出现映射差异(截图:
),对应的请求载荷如下:
{ sample: { sampleOne: { name: 'sample name', type: SampleTypes.STRING, example: 'sample example', } as SampleItem, }, description: 'description' }
2. Record<string, any> 字段映射报错
请求载荷
{ description: { des: 'description' } as Record<string, any>, }
报错信息
Original error: Error: Mapping is not found for function String() { [native code] } and function String() { [native code] } at setMember (/home/fabiofilho/Projects/project/node_modules/@automapper/core/index.cjs:379:15) at map (/home/fabiofilho/Projects/project/node_modules/@automapper/core/index.cjs:439:9) at mapReturn (/home/fabiofilho/Projects/project/node_modules/@automapper/core/index.cjs:291:10) at Proxy.<anonymous> (/home/fabiofilho/Projects/project/node_modules/@automapper/core/index.cjs:691:31)
相关配置细节(使用 ttypescript)
依赖版本
"dependencies": { "@automapper/classes": "^8.7.5", "@automapper/core": "^8.7.5", "@automapper/mikro": "^8.7.5", "@automapper/nestjs": "^8.7.5", "@automapper/pojos": "^8.7.5", "@automapper/sequelize": "^8.7.5", }
ts-jest 配置
module.exports = { [...] globals: { 'ts-jest': { compiler: 'ttypescript', }, }, };
内容的提问来源于stack exchange,提问作者Fábio Filho
相关产品推荐
相关产品推荐

