这篇文章是关于如何在Elm中以以下格式编码和解码简单的自定义类型:
type MyCustomType
= A
| B
| C
这是有关如何编码和解码任何自定义类型的快速简单的演示。
假设您具有这样的自定义类型:
type MyCustomType
= A
| B
| C
您可以直接将MyCustomType
编码为字符串:
encodeMyCustomType : MyCustomType -> Encode.Value
encodeMyCustomType myCustomType =
Encode.string <|
case myCustomType of
A -> "A"
B -> "B"
C -> "C"
解码MyCustomType
稍微复杂一些。您需要使用Decode.andThen
检查找到的变体,并在没有找到有效变体的情况下使用Decode.andThen
:
Decode.fail