Search code examples
typesocamlffiabstract-data-typebucklescript

Empty Type Declaration


What happens when one declares a type without binding it to anything:

type a_type
type b_type

let a : a_type = (* ? *)

I ran into this while reading BuckleScript FFI manual. The code for binding to a JS object looks like this:

type t
external create_date : unit -> t = "Date" [@@bs.new]
let date = create_date ()

BuckleScript's specificities aside, t is used as a valid type, which in this case looks like it's acting as a polymorphic type for a generic external JS type.

I have to apologize for asking such rudimentary question, but this is not documented anywhere I've looked into. Any pointers are appreciated.


Solution

  • It's called an abstract type, and is usually used to hide the structure of the underlying data, but is particularly useful with BuckleScript because the underlying JavaScript structure isn't necessarily even representable as a native OCaml type.

    It's not polymorphic, however, just an opaque type.

    The nature of FFI might complicate the concept a bit, though. Foreign "functions" are by definition untyped, and the process of defining an FFI using externals is one where you tell the compiler what the types of these functions are. So you could tell the compiler that toString returns an int if you want, and it won't know the difference until you actually try to use it as an int, which will of course end badly.

    But since abstract types are user-defined and don't have structure you'll have to define all the functions that can operate on it yourself, via the FFI. You can't manipulate it in OCaml (unless you circumvent the type system at least), so it's just a black box that enables you to carry a value from one FFI function to another.