Serializable icon indicating copy to clipboard operation
Serializable copied to clipboard

support generic

Open dearming623 opened this issue 9 months ago • 1 comments

Can generic nesting be supported?

import { jsonName, jsonProperty, Serializable } from "ts-serializable";

export class ApiResponse<T> extends Serializable {

@jsonName("code")
@jsonProperty(String, null)
public code: string | null = null;

@jsonName("msg")
@jsonProperty(String, null)
public message: string | null = null;

@jsonName("data")
@jsonProperty(Object, null)
public data: T | null = null;

}

use like: const res = new ApiResponse<User>().fromJSON(respJson);

dearming623 avatar Apr 07 '25 10:04 dearming623

Unfortunately, TypeScript does not provide any information about generics at runtime. Therefore, they cannot be used directly, but you can create a closed version of the generic and use it for deserialization.


class ClosedGeneric extends Generic<Sample> {
    public sample: Sample | null = null;
}

...
export class ApiResponse extends Serializable {
    @jsonProperty(ClosedGeneric, null)
    public data: ClosedGeneric | null = null;
}

LabEG avatar Apr 10 '25 20:04 LabEG