HarmonyOS 无法使用class-transformer中的@Type注解

定义嵌套类型,代码如下:

import { Type, Expose, instanceToPlain, plainToClass, instanceToInstance } from 'class-transformer';  
export class User {  
  @Expose({name: 'user_id'})  
  uid: number = 0;  
  @Expose({name: 'user_name'})  
  userName: string = '';  
  @Expose({name: 'source_type'})  
  sourceType: string = '';  
  @Expose({name: 'is_leader'})  
  isLeader: boolean = false;  
  @Expose({name: 'role_name'})  
  roleName: string = '';  
  constructor(id: number, name: string, type: string, isLeader: boolean, roleName: string) {  
    this.uid = id;  
    this.userName = name;  
    this.sourceType = type;  
    this.isLeader = isLeader;  
    this.roleName = roleName;  
  }  
  static fromPlain(plain: object): User {  
    return plainToClass(User, plain);  
  }  
  toJson(): string {  
    return JSON.stringify(instanceToPlain(this));  
  }  
}  
export class UserResponse {  
  @Type(() => User)  
  user: User;  
  constructor(user: User) {  
    this.user = user;  
  }  
  static fromPlain(plain: object): UserResponse {  
    return plainToClass(UserResponse, plain);  
  }  
  toJson(): string {  
    return JSON.stringify(instanceToPlain(this));  
  }  
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.

运行程序报错:

Pid:34987  
Uid:20020002  
Reason:TypeError  
Error name:TypeError  
Error message:is not callable  
SourceCode:  
        var reflectedType = Reflect.getMetadata('design:type', target, propertyName);  
                            ^  
Stacktrace:  
SourceMap is not initialized yet   
    at anonymous (oh_modules/.ohpm/class-transformer@0.5.1/oh_modules/class-transformer/esm5/decorators/type.decorator.js:11:29)  
    at func_main_0 (commons/datastore/src/main/ets/model/User.ets:1:1)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
HarmonyOS
2024-10-10 12:01:06
1.0w浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
superinsect

使用@Type装饰器的时候,确保引入reflect-metadata。在ability里import reflect-metadata。

分享
微博
QQ
微信
回复
2024-10-10 18:02:52


相关问题
HarmonyOS class-transformer问题
1173浏览 • 1回复 待解决
HarmonyOS class-transformer三方库Json转class
575浏览 • 1回复 待解决
HarmonyOS 使用了@Sendable注解类报错
672浏览 • 1回复 待解决
HarmonyOS 如何在ArkTS中使用注解
823浏览 • 1回复 待解决
嵌套Class属性变化无法触发UI渲染
769浏览 • 1回复 待解决
HarmonyOS class显示CustomDialog
396浏览 • 1回复 待解决