This is the latest docs version
Quick Links
  • -Overview
  • -Language Features
  • -JS Interop
  • -Build System
Documentation
Language Manual
Reference for all language features
ReScript & React
First class bindings for ReactJS
GenType
Seamless TypeScript integration
Reanalyze
Dead Code & Termination analysis
Exploration
Packages
Explore third party libraries and bindings
Syntax Lookup
Discover all syntax constructs
APIPlaygroundBlogCommunity
  • Playground
  • Blog
  • X
  • Bluesky
  • GitHub
  • Forum
Language Manual
Overview
  • Introduction
  • Installation
  • Migrate to v11
  • Editor Plugins
  • Try
Language Features
  • Overview
  • Let Binding
  • Type
  • Primitive Types
  • Tuple
  • Record
  • Object
  • Variant
  • Polymorphic Variant
  • Null, Undefined and Option
  • Array & List
  • Function
  • If-Else & Loops
  • Pipe
  • Pattern Matching / Destructuring
  • Mutation
  • JSX
  • Exception
  • Lazy Value
  • Promises
  • Async / Await
  • Tagged templates
  • Module
  • Import & Export
  • Attribute (Decorator)
  • Reserved Keywords
  • Equality and Comparison
Advanced Features
  • Extensible Variant
  • Scoped Polymorphic Types
  • Module Functions
    • Quick example
    • Sharing a type with an external binding
    • Shared functions
    • Dependency injection
JavaScript Interop
  • Interop Cheatsheet
  • Embed Raw JavaScript
  • Shared Data Types
  • External (Bind to Any JS Library)
  • Bind to JS Object
  • Bind to JS Function
  • Import from / Export to JS
  • Bind to Global JS Values
  • JSON
  • Inlining Constants
  • Use Illegal Identifier Names
  • Generate Converters & Helpers
  • Browser Support & Polyfills
  • Libraries & Publishing
  • TypeScript
Build System
  • Overview
  • Configuration
  • Configuration Schema
  • External Stdlib
  • Pinned Dependencies
  • Interop with JS Build Systems
  • Performance
  • Warning Numbers
Guides
  • Converting from JS
Extra
  • Newcomer Examples
  • Project Structure
  • FAQ
Docs / Language Manual / Module Functions
Edit

Module Functions

Module functions can be used to create modules based on types, values, or functions from other modules. This is a powerful tool that can be used to create abstractions and reusable code that might not be possible with functions, or might have a runtime cost if done with functions.

This is an advanced part of ReScript and you can generally get by with normal values and functions.

Quick example

Next.js has a useParams hook that returns an unknown type, and it's up to the developer in TypeScript to add a type annotation for the parameters returned by the hook.

TS
const params = useParams<{ tag: string; item: string }>()

In ReScript we can create a module function that will return a typed response for the useParams hook.

ReScriptJS Output
module Next = {
  // define our module function
  module MakeParams = (Params: { type t }) => {
    @module("next/navigation")
    external useParams: unit => Params.t = "useParams"
    /* You can use values from the function parameter, such as Params.t */
  }
}

module Component: {
  @react.component
  let make: unit => Jsx.element
} = {
  // Create a module that matches the module type expected by Next.MakeParams
  module P = {
    type t = {
      tag: string,
      item: string,
    }
  }

  // Create a new module using the Params module we created and the Next.MakeParams module function
  module Params = Next.MakeParams(P)

  @react.component
  let make = () => {
    // Use the functions, values, or types created by the module function
    let params = Params.useParams()
    <div>
      <p>
        {React.string("Tag: " ++ params.tag /* params is fully typed! */)}
      </p>
      <p> {React.string("Item: " ++ params.item)} </p>
    </div>
  }
}

Sharing a type with an external binding

This becomes incredibly useful when you need to have types that are unique to a project but shared across multiple components. Let's say you want to create a library with a getEnv function to load in environment variables found in import.meta.env.

RES
@val external env: 'a = "import.meta.env" let getEnv = () => { env }

It's not possible to define types for this that will work for every project, so we just set it as 'a and the consumer of our library can define the return type.

RES
type t = {"LOG_LEVEL": string} let values: t = getEnv()

This isn't great and it doesn't take advantage of ReScript's type system and ability to use types without type definitions, and it can't be easily shared across our application.

We can instead create a module function that can return a module that has contains a getEnv function that has a typed response.

RES
module MakeEnv = ( E: { type t }, ) => { @val external env: E.t = "import.meta.env" let getEnv = () => { env } }

And now consumers of our library can define the types and create a custom version of the hook for their application. Notice that in the JavaScript output that the import.meta.env is used directly and doesn't require any function calls or runtime overhead.

ReScriptJS Output
module Env = MakeEnv({
	type t = {"LOG_LEVEL": string}
})

let values = Env.getEnv()

Shared functions

You might want to share functions across modules, like a way to log a value or render it in React. Here's an example of module function that takes in a type and a transform to string function.

RES
module MakeDataModule = ( T: { type t let toString: t => string }, ) => { type t = T.t let log = a => Console.log("The value is " ++ T.toString(a)) module Render = { @react.component let make = (~value) => value->T.toString->React.string } }

You can now take a module with a type of t and a toString function and create a new module that has the log function and the Render component.

ReScriptJS Output
module Person = {
  type t = { firstName: string, lastName: string } 
  let toString = person => person.firstName ++ person.lastName
}

module PersonData = MakeDataModule(Person)

Now the PersonData module has the functions from the MakeDataModule.

ReScriptJS Output
@react.component
let make = (~person) => {
  let handleClick = _ => PersonData.log(person)
  <div>
    {React.string("Hello ")}
    <PersonData.Render value=person />
    <button onClick=handleClick>
      {React.string("Log value to console")}
    </button>
  </div>
}

Dependency injection

Module functions can be used for dependency injection. Here's an example of injecting in some config values into a set of functions to access a database.

ReScriptJS Output
module type DbConfig = {
  let host: string
  let database: string
  let username: string
  let password: string
}

module MakeDbConnection = (Config: DbConfig) => {
  type client = {
    write: string => unit,
    read: string => string,
  }
  @module("database.js")
  external makeClient: (string, string, string, string) => client = "makeClient"

  let client = makeClient(Config.host, Config.database, Config.username, Config.password)
}

module Db = MakeDbConnection({
  let host = "localhost"
  let database = "mydb"
  let username = "root"
  let password = "password"
})

let updateDb = Db.client.write("new value")
Scoped Polymorphic TypesInterop Cheatsheet

© 2024 The ReScript Project

Software and assets distribution powered by KeyCDN.

About
  • Community
  • ReScript Association
Find us on