json2typescript
json2typescript copied to clipboard
Consider adding generic type as parameter for custom converters
This is a proposal, and may not be the correct way of doing stuff. My goal is to implement a generic custom converter for string based enums, and I think this would allow that.
Whilst trying to write a generic custom converter for string based Enum types, I find that the current design of JsonCustomConvert will not allow such behavior (to my knowledge).
I was thinking about implementing a design such as:
import {JsonConverter, JsonCustomConvert} from "json2typescript";
@JsonConverter
export class EnumConverter<T extends any> implements JsonCustomConvert<T> {
serialize(value: T): string {
return value.toString();
}
deserialize<T extends any>(data: string, t: T): T {
return t[data] as T;
}
}
The current JsonCustomConvert-interface only includes data as a parameter. What I am proposing is adding a second parameter, type, which passes the generic type on.
Interface today:
deserialize(data: any): T;
my proposal:
deserialize(data: any, type: T): T;
This will allow us to access the types value in the converter, allowing for a generic custom enum converter.
Perhaps I am doing something wrong? :)
I am not sure if it is possible, but you are welcome to make a pull request! I do not know at the moment when I will be investing time in development again, but I will keep this issue open for this purpose.
@andreas-aeschlimann I will see what I can do
Have you found any solution for this proposal?
Not yet, unfortunately.
Can it be done, considering that generics are gone in the JS compilation?