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
1

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.