Quantcast
Channel: ReScript Forum - Latest posts
Viewing all articles
Browse latest Browse all 2592

Variant with generic "mysterious" behaviour

$
0
0

Hello, dear community,

I’ve stumbled upon an interesting behaviour of the variant type. Here’s an example:

module Post = {
  type t = {userId: int}

  let decode = (_t: Js.Json.t): result<t, string> => {
    Ok({userId: 1}) // some decoding is happening here...
  }
}

module Http = {
  type expect<'t> =
    | ExpectJson(Js.Json.t => result<'t, string>)
    | ExpectText(string => result<string, string>)

  // imagine it takes some url as well...
  let get = async (expect: expect<'t>): result<'t, string> => {
    switch expect {
    | ExpectJson(dec) => dec(Js.Json.Null)
    | ExpectText(val) => val("")
    }
  }
}

Http.get(Http.ExpectJson(Post.decode)) // compiler is sceptical here...
---

This has type: Js.Json.t => result<Post.t, string>
  But it's expected to have type: Js.Json.t => result<string, string>
  
  The incompatible parts:
    Post.t vs string

Can someone explain why this is the case? The types are explicit… when handling a JSON response we need a decoder, when handling a text response, the function validates the string… So, why type mismatch?

Thank you in advance!


Viewing all articles
Browse latest Browse all 2592

Trending Articles