How to Encode and Decode Simple Custom Types in Elm?

Viewed 715

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
1 Answers

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"
    )
Related