You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I want to deserialize an enum property without ReflectDecorators:
enumColor{red="RED",green="GREEN",blue="BLUE"}
@jsonObjectclassThing{
@jsonMember({what: "todo?"})publiccolor?: Color}console.log(TypedJSON.parse('{"color": "green"}',Thing));// should log Object { color: "green" }console.log(TypedJSON.parse('{"color": "infradead"}',Thing));// should throw error
How do I populate those @jsonMember options to achieve this? Enum types don't have a constructor.
The only solution I've found is:
functiondeserializeColor(value: string): Color{constkeyValue=valueaskeyoftypeofColor;if(keyValueinColor){returnColor[keyValue];}else{thrownewSyntaxError(`${keyValue} is not a valid Color`);}};
@jsonObjectclassThing{
@jsonMember({deserializer: deserializeColor})publiccolor?: Color}
but that's pretty verbose, and requires a separate deserializer function for each enum type (or at least I haven't found a workable way to make it generic).
The text was updated successfully, but these errors were encountered:
I understand it's perhaps not the most intuitive thing ever, but in the meantime, for your exact example, you have to think with the runtime code here, i.e. that your enum is in fact a string at runtime. As such, you should specify String as the member constructor (which is the same as the stringprimitive for TypedJSON):
If you properly value-check and throw in your setter, the TypedJSON.parse call should throw on invalid values (assuming your error handler does as well, which is the default behavior). This can be simplified by using a custom decorator that value-checks assignments, as jsonMember can be used with other decorators.
I want to deserialize an enum property without ReflectDecorators:
How do I populate those
@jsonMember
options to achieve this? Enum types don't have a constructor.The only solution I've found is:
but that's pretty verbose, and requires a separate deserializer function for each enum type (or at least I haven't found a workable way to make it generic).
The text was updated successfully, but these errors were encountered: