How to get the type of a module?

If I do a module type Foo =. … I can reference that module type in other places. But suppose I want to get the type of a module that has an resi file. How do I do that? And how to get the type of a module in a res file without an explicit resi file?

1 Like
module M = {
  let x = 1
}

module M2: module type of M = {
  let x = 2
}

Works the same way for any module, whether it’s a res file, with or without a resi file, or purely a syntactic module.

3 Likes

I keep running into problems with the syntax. Is there some way to do this on one line?

module type UserType = module type of UserId
// works
let userId1: module(UserType) = module(UserId)

// does not work
let userId2: module(module type of UserId) = module(UserId)
let userId3: module(type of UserId) = module(UserId)
let userId4: module(include (module type of UserId)) = module(UserId)

Unless ReScript is being quite different than OCaml here, then I don’t think you will be able to do it in one line.

Here is a quote from the OCaml docs about what kind of module types can be used to annotate as you’re trying to do

The package-type syntactic class appearing in the ( module package-type ) type expression and in the annotated forms represents a subset of module types. This subset consists of named module types with optional constraints of a limited form: only non-parametrized types can be specified.

So you have to used named types here. If you follow back the grammar in the linked docs you’ll see that as well.

If you write it slightly differently, you can cut the verbosity a bit as well.

module UserId = {
  type t = string
  let id = t => t
}

// Only one extra line
module type UserType = module type of UserId

// You can annotate right in the `module` part
let f = (t, module(M: UserType)) => M.id(t)

// This one doesn't even need annotation.
let id = f("yo", module(UserId))

// This does, but it's not so bad when you put it in the expression itself.
let userId = module(UserId: UserType)
let id' = f("hey", userId)

Edit: playground