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