DEV Community

loading...

Discussion on: Decoding JSON with Typescript

Collapse
joanllenas profile image
Joan Llenas Masó Author

I'm aware of io-ts but I haven't jumped on the fp-ts bandwagon yet. The learning curve seems quite steep.

The decoder you just mentioned would fail at compile-time, because number and string are different types.
If the data you want to decode is a number but you want a string you could do:

const userDecoder = JsonDecoder.object<User>(
  {
    firstName: JsonDecoder.string,
    lastName: JsonDecoder.string,
    age: JsonDecoder.number.map(num => num.toString())
  },
  'User'
)

Cheers!