Can anyone explain "type t"?

For example, this one https://rescript-lang.org/docs/manual/latest/api/js/json

I don’t know keyword I should use to search this so I create a new topic. Is it some kind of convention or “t” has a special meaning?

1 Like

Yes it is a convention.

Generally each module exposes a type called t and operations on that type.

A clear explaination could be found in the last section Types and modules of this page.
Custom Data Types – OCaml

2 Likes

It is a convention for organizing types and functions that each type is defined inside a module and given the name “t”. The module holds functions that primarily operate on that specific type. For example…

module Point = {
type t = { x:int, y: int }
let make = …
let invert = …
let distanceBetween = (p1, p2) …

If the type t has no details about what it contains that means it is abstract. You’re not supposed to know what data is used to store it and you just work with it using the associated functions.

If you later we’re defining a type Line, you’d often define it like…

module Line = {
type t = { p1: Point.t, p2: Point.t }

This is not the only way to organize types and functions. I found this interesting…

3 Likes

In general, a good way to organize your code so that each module has one “main” type, and all of its functions work with that type. the Js.Json module is a good example. It has one main type, Js.Json.t, which represents JSON data, and all of its functions work with that type, i.e. Js.Json.decodeString etc.

In practice, the “main” type can be named anything. You could call it type json or type data or whatever you want. Calling it t is just a convention, but it has a few advantages:

  1. If the type was called json, then its full name Js.Json.json would look redundant.
  2. Since a module’s main type gets used a lot, then giving it a short, one-character long name saves us a lot of screen space. t, as an abbreviation of “type,” makes sense.
  3. When everything uses the same convention, then reading signatures for different modules becomes a lot easier. A function Js.Json.t => option<string> takes JSON data and tries to return a string (Js.Json.decodeString). A function Js.Date.t => string takes a date and returns a string (Js.Date.toString).
  4. Another, more advanced, benefit of everything using the same convention is that it enables us to combine modules together with functors and first-class modules.
2 Likes