How to Encode and Decode Simple Custom Types in Elm?
Asked Answered
A

1

5

In Elm, there's no native way to encode/decode a custom type. This makes send and receive custom-typed values to JS difficult. I was confused for a while and wonder how to handle simple custom types like the one below?

type MyCustomType
  = A
  | B
  | C
Andro answered 17/5, 2020 at 19:58 Comment(1)
#57245484 I think this is a duplicate of that question, but this question is formulated a lot more generallyChlamydospore
A
7

Here's a quick and simple demo of how to encode and decode any custom types.

Say you have a custom type like this:

type MyCustomType
  = A
  | B
  | C

You can encode MyCustomType directly as a string:

encodeMyCustomType : MyCustomType -> Encode.Value
encodeMyCustomType myCustomType =
  Encode.string <|
    case myCustomType of
      A -> "A"
      B -> "B"
      C -> "C"

Decoding MyCustomType is slightly more involved. You need to use Decode.andThen to check which variant is found and use Decode.fail in case no valid variant is found:

Decode.string |>
  Decode.andThen
    (\str ->
      case str of
        "A" -> Decode.succeed A
        "B" -> Decode.succeed B
        "C" -> Decode.succeed C
        _ -> Decode.fail "Invalid MyCustomType"
    )
Andro answered 17/5, 2020 at 19:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.