如何解码 Elm 中的静态值

问题描述

使用 Json.decode 是否可以解码静态值,例如 Json 不包含值,但我希望本地类型别名具有更多具有认值的数据。我怎样才能做到这一点?谢谢!

解决方法

有两种方法可以做到这一点,

使用Decode.succeeded

import Json.Decode as Decode

-- snip

Decode.map2 Item
    (Decode.field "title" Decode.string)
    (Decode.succeed 0)

(其中 Item 是任意的 type alias


或者使用闭包

Decode.map (\name -> {name = name,age = 42} ) (Decode.field "name" Decode.string)