DEV Community

loading...

Discussion on: Decoding JSON with Typescript

Collapse
hmendezm profile image
H. Mendez

HI everybody.

I am using the JsonDecoder and I have two issues that I do not know how to solv.

  1. how I represent any type
  2. I have class functions that are public and JsonDecoder asks me to add them. How should I handle this situation?

(alias) namespace JsonDecoder
import JsonDecoder
Argument of type '{ optionID: Decoder; name: Decoder; study: any; workflowId: Decoder; workflow: Decoder; scenarios: Decoder; disabled: Decoder; defaultTask: Decoder<...>; }' is not assignable to parameter of type 'DecoderObject'.
Type '{ optionID: Decoder; name: Decoder; study: any; workflowId: Decoder; workflow: Decoder; scenarios: Decoder; disabled: Decoder; defaultTask: Decoder<...>; }' is missing the following properties from type 'DecoderObject': getTaskByID, getScenarioByID, addScenario, updateScenario, getPreviousTaskts
Best,
Hmendezm

Collapse
joanllenas profile image
Joan Llenas Masó Author

You can decode the methods with JsonDecoder.succeed:

...
getTaskByID: JsonDecoder.succeed
...

but the class will lose all the instance information during the decoding process. If you are using the instanceof operator later on it won't work. Aside from that, you are good to go.

Collapse
hmendezm profile image
H. Mendez

Hey Joan, sorry for bothering you again.

I have a case where the columns from the JSON can be with different for instance the JSON can have _color: yellow or color: yellow.

I am using the keyMap for the _color and I thought that if the column does not exist will take color but it is not the case. How can I have more the one keymap option?

Best
Hmendezm

Collapse
hmendezm profile image
H. Mendez

Hi Joan, sorry for bothering you. U have a case when the property in the class can be a number or null. How I can set a default value when it is null?

Best
Hmendezm

Collapse
hmendezm profile image
H. Mendez

Thanks, Joan for the help.