type-safe-json-decoder icon indicating copy to clipboard operation
type-safe-json-decoder copied to clipboard

I have objects with more than 14 fields :(

Open radix opened this issue 7 years ago • 6 comments

Hi!

I am in the unfortunate situation of having objects with more than 14 fields, and the object function only supports up to that many (at least, in a type-safe way). Does it make sense to just add more type declarations (I hope TS itself doesn't have a limit on the number of type variables...) or should there be some other more incremental API for decoding objects with large number of fields?

Elm's Json.Decoder only supports up to 5 fields at a time, but there is another package called elm-decode-pipeline which supports a more flexible framework for decoding these large objects. You use a syntax like this:

decode User
  |> required "id" int
  |> required "email" string
  |> optional "name" string ""

where decode and required have these type signatures:

decode : a -> Decoder a
required : String -> Decoder a -> Decoder (a -> b) -> Decoder b

however, I have no idea if TypeScript supports the type trickery required for a API like this.

radix avatar Jun 09 '17 19:06 radix

The ergonomics of the Elm pipeline decoder package rely pretty heavily on currying a constructor. We could probably do some strange things with functions and get a similar system working but I think I have a better idea.

I have a hunch that we could get something working with Intersection Types where we allow function chaining like().this().maybe() to incrementally & generic types together to build the final result. I'll give it a go tomorrow after I get some rest.

Although TypeScript and Elm solve a similar problem, they have very different type systems and it's been fun to feel the bits where this library diverges from a 1-to-1 clone of Elm's Json.Decode

ooesili avatar Jun 10 '17 06:06 ooesili

@ooesili Just fwiw, this isn't urgent for me. I figured out a workaround by declaring a type in my own code that supports the number of arguments I need (up to 16 now :P), so I have a passable workaround for the time being.

Thanks for the response!

radix avatar Jun 10 '17 16:06 radix

Hey @radix, would you mind elaborating a little bit how your workaround works? I need to support more than 15 fields. Thanks!

joanllenas avatar Mar 07 '18 12:03 joanllenas

Maybe this could be helpful https://github.com/darekzak/type-safe-json-decoder. Basically I merged MazeChaZer implementation of object decoder, so kudos to him.

darekzak avatar Mar 07 '18 13:03 darekzak

@joanllenas See here: https://github.com/radix/pandt/blob/92f0ecc8e085dcb4c32e62973e10a00fac86e8a5/ptui/src/PTTypes.ts#L527-L555

radix avatar Mar 07 '18 15:03 radix

Thanks @darekzak @radix for you quick responses, I'll check and see which option better suits my needs. Cheers

joanllenas avatar Mar 07 '18 16:03 joanllenas