Is `type as` documented anywhere?

I’m trying to do some bizarre stuff with poly variants. I suspect what I want to do is not possible (and should not be possible), and I’ll follow up with some questions once I figure out what those questions are. :smiley:

In the meantime, I have a simpler question. I noticed in the lower bound docs that a type is being assigned as a:

type basicBlueTone<'a> = [> #Blue | #DeepBlue | #LightBlue ] as 'a

Intuitively, I can see what’s going on here, but I want to know how far I can push it. Can I define a type with a as generic parameter as well as other fields, for example?

I found the (lack of) docs on covariance ticket, but I can’t tell if it’s a related concept.

2 Likes

Hi, perhaps this will help: OCaml - Labels and variants

If you want something with fields, I assume you mean an object, in which case yes:

type person<'a> = {
  ..
  "id": int,
  "name": string,
} as 'a

This means that the type person has at least the id and name fields, and possibly more. Here we’re defining the type explicitly, which we sometimes need to do; more commonly, it is inferred from usage, like:

let greet = person => {
  print_int(person["id"]) // int argument
  print_endline("")
  print_endline(person["name"]) // string argument
}
3 Likes

I’m trying to get my head around this stuff at the moment to support expandable Result.t error types and although I’m still trying to get my head around the covariant/contravariant annotations, I found the information on OCaml objects useful (as the implementation and hence type system implications) are similar:

https://dev.realworldocaml.org/objects.html

This may be relevant for you: https://github.com/yawaramin/prometo/blob/ef7229d3cbfe9980e32feef8e882785b49a96434/src/Yawaramin__Prometo.rei#L15

It is in Reason syntax but obviously there is a direct correspondence to ReScript.

1 Like