DEV Community

Discussion on: Decoding JSON with Typescript

Collapse
 
blocka profile image
Avi Block

Have you seen io-ts? io-ts also removes the duplication by creating a "decoder" and a type at the same time.

interface User {
  firstName: string;
  lastName: string;
  age: string;
}

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

what would happen in this case?

Collapse
 
joanllenas profile image
Joan Llenas Masó • Edited

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!