Fable - 无法获取通用参数的类型信息,请内联或注入类型解析器

Fable - Cannot get type info of generic parameter, please inline or inject a type resolver

我正在尝试在寓言中编写一个通用的 json 解码函数。它似乎在 FSharp 中编译,但我收到此代码的错误消息:

[使用 Thoth.Json 库和来自 Fable.PowerPack 的 Fetch 库]

let autoDecoder<'a> (json:string) (value:obj) : Result<'a, Thoth.Json.Decode.DecoderError> =
    let tryDecode = Thoth.Json.Decode.Auto.fromString<'a>(json)
    let getDecoderError (str:string) : Thoth.Json.Decode.DecoderError = ( "Auto decode Error", Thoth.Json.Decode.FailMessage str) 
    Result.mapError getDecoderError tryDecode

错误寓言:无法获取泛型参数的类型信息,请内联或注入类型解析器

我不确定如何解决这个问题,并且在 google 上找不到任何内容。

我希望能够在 Fable Elmish 的更新函数中调用这样的函数:

let update (msg:Msg) (model:Model) =
    match msg with
..
    | OrStart ->
        let getData() = Fetch.fetchAs<ResultResponse>  "https://randomuser.me/api/" json.autoDecoder<ResultResponse> http.getHeaders
        model, Cmd.ofPromise getData () LoadedTypedData FetchError

如何在保持通用性的同时编译 autoDecoder<'a> 函数?

谢谢

我是 fable 的新手,我无法让它工作,fable 编译器不允许在没有指定类型的情况下自动解码 - 此处失败:

Thoth.Json.Decode.Auto.fromString<'a>(str, true)

但是对于那些在 fable 中努力获取 api 的人来说,这可以用不太多的样板代码来完成。我无法得到通用的承诺,但是像 getCustomers 这样的特定类型的实现非常简洁,我最终做了这样的事情:

type Msg =
    | Start
    | LoadedCustomerData of Result<QueryDataForJson, string>
..

let getCustomers () = promise {
    let! response = Fetch.fetch "http://localhost:5000/spa/api/customers" http.getHeaders
    let! text = response.text()
    return Thoth.Json.Decode.Auto.fromString<QueryDataForJson>(text, true)
}
..
let update (msg:Msg) (model:Model) =
    match msg with
    | Start ->
        model, Cmd.ofPromise getCustomers () LoadedCustomerData FetchError
    | LoadedCustomerData resp ->
        match resp with
            | Ok qdj -> { model with gridData= queryDataFromJson qdj; message= "Loaded Customer Data"  }, Cmd.none
            | Error str -> { model with message = str }, Cmd.none

我认为 Fable 是在告诉你像这样使用 inline

let inline autoDecoder<'a> (json:string) (value:obj) : Result<'a, Thoth.Json.Decode.DecoderError> =
    let tryDecode = Thoth.Json.Decode.Auto.fromString<'a>(json)
    let getDecoderError (str:string) : Thoth.Json.Decode.DecoderError = ( "Auto decode Error", Thoth.Json.Decode.FailMessage str) 
    Result.mapError getDecoderError tryDecode

这是因为像内联函数一样的泛型函数需要在每次调用时实例化。

顺便说一句,value 参数没有被使用。

你也可以这样精简代码:

let inline autoDecoder<'a> (json:string) : Result<'a, Thoth.Json.Decode.DecoderError> =
    Thoth.Json.Decode.Auto.fromString<'a> json
    |> Result.mapError (fun (str:string) ->  "Auto decode Error", Thoth.Json.Decode.FailMessage str)