Array of Enum values
Closed this issue · 4 comments
I have a jsonArrayMember that looks like the following:
@jsonObject
export class Item {
...
@jsonArrayMember(String)
gemSockets: GemSocketColor[] = [];
...
}
export enum GemSocketColor {
yellow = 'yellow',
blue = 'blue',
red = 'red',
green = 'green',
}
and then later on in the program
const json = this.serializer.stringify(this.item)` //works and gives me the JSON representation
this.serializer.parse(json) || new Item(); // throws TypeError: Could not deserialize gemSockets as Array: incorrect TypeDescriptor detected, please use proper annotation or function for this type
NOTE: I have to have the || new Item()
on the end otherwise Typescript throws a fit saying that "Item | Undefined cannot be assigned to type Item"
What happens if you swap the order, i.e. move GemSocketColor
before Item
?
Hi @westlakem, there is one more thing to check. Are you by any chance running in typescript strict null checking mode? If so, you may want to try the latest rc version - 1.7.0-rc3 where we have a fix for that.
btw. if you are sure that TypedJSON will be able to deserialise your object you can just use a non null assertion by adding a !
just after the parse like this:
this.serializer.parse(json)!;
@JohnWeisz @Neos3452 Neither of those solutions worked.
I ended up switching to use the typescript-json-serializer package that worked right out of the box.
Sorry to hear that. It would be really awesome if you could provide more info on your case as your code works for me in both normal and strict mode. Below prints {"gemSockets":["blue","green"]}
, and Item { gemSockets: [ 'blue', 'green' ] }
which is expected.
@jsonObject
class Item {
@jsonArrayMember(String)
gemSockets: Array<GemSocketColor> = [];
}
enum GemSocketColor {
yellow = 'yellow',
blue = 'blue',
red = 'red',
green = 'green',
}
const item = new Item();
item.gemSockets = [GemSocketColor.blue, GemSocketColor.green];
const json = TypedJSON.stringify(item, Item);
console.log(json);
const parsed = TypedJSON.parse(json, Item);
console.log(parsed);