json2typescript icon indicating copy to clipboard operation
json2typescript copied to clipboard

Consider adding generic type as parameter for custom converters

Open ErlendEllingsen opened this issue 6 years ago • 4 comments

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? :)

ErlendEllingsen avatar Jun 03 '19 13:06 ErlendEllingsen

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 avatar Jun 26 '19 19:06 andreas-aeschlimann

@andreas-aeschlimann I will see what I can do

ErlendEllingsen avatar Jul 30 '19 08:07 ErlendEllingsen

Have you found any solution for this proposal?

eduard2014 avatar Dec 30 '19 12:12 eduard2014

Not yet, unfortunately.

Can it be done, considering that generics are gone in the JS compilation?

andreas-aeschlimann avatar Jan 08 '20 12:01 andreas-aeschlimann