首页 > 解决方案 > 寓言 - 无法获取泛型参数的类型信息,请内联或注入类型解析器

问题描述

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

[使用来自 Fable.PowerPack 的 Thoth.Json 库和 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

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

我不知道如何解决这个问题,也无法在谷歌上找到任何东西。

我希望能够在 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> 函数,同时保持它的通用性?

谢谢

标签: f#fable-f#

解决方案


我认为 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) 

推荐阅读