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
  • Twitter
  • 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
    • Definition and Usage
    • Limitations of Normal Polymorphic Types
    • Limitations of Scoped Polymorphic Types
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 / Scoped Polymorphic Types
Edit

Scoped Polymorphic Types

Scoped Polymorphic Types in ReScript are functions with the capability to handle arguments of any type within a specific scope. This feature is particularly valuable when working with JavaScript APIs, as it allows your functions to accommodate diverse data types while preserving ReScript's strong type checking.

Definition and Usage

Scoped polymorphic types in ReScript offer a flexible and type-safe way to handle diverse data types within specific scopes. This documentation provides an example to illustrate their usage in a JavaScript context.

Example: Logging API

Consider a logging example within a JavaScript context that processes various data types:

JS
const logger = { log: (data) => { if (typeof data === "string") { /* handle string */ } else if (typeof data === "number") { /* handle number */ } else { /* handle other types */ } }, };

In ReScript, we can bind to this function as a record with a scoped polymorphic function type:

RES
type logger = { log: 'a. 'a => unit } @module("jsAPI") external getLogger: unit => logger = "getLogger"

The logger type represents a record with a single field log, which is a scoped polymorphic function type 'a. 'a => unit. The 'a indicates a type variable that can be any type within the scope of the log function.

Now, we can utilize the function obtained from getLogger:

ReScriptJS Output
let myLogger = getLogger()

myLogger.log("Hello, ReScript!")
myLogger.log(42)

In this example, we create an instance of the logger by calling getLogger(), and then we can use the log function on the myLogger object to handle different data types.

Limitations of Normal Polymorphic Types

Let's consider the same logging example in ReScript, but this time using normal polymorphic types:

RES
type logger<'a> = { log: 'a => unit} @module("jsAPI") external getLogger: unit => logger<'a> = "getLogger"

In this case, the logger type is a simple polymorphic function type 'a => unit. However, when we attempt to use this type in the same way as before, we encounter an issue:

RES
let myLogger = getLogger() myLogger.log("Hello, ReScript!") myLogger.log(42) // Type error!

The problem arises because the type inference in ReScript assigns a concrete type to the logger function based on the first usage. In this example, after the first call to myLogger, the compiler infers the type logger<string> for myLogger. Consequently, when we attempt to pass an argument of type number in the next line, a type error occurs because it conflicts with the inferred type logger<string>.

In contrast, scoped polymorphic types, such as 'a. 'a => unit, overcome this limitation by allowing type variables within the scope of the function. They ensure that the type of the argument is preserved consistently within that scope, regardless of the specific value used in the first invocation.

Limitations of Scoped Polymorphic Types

Scoped polymorphic types work only when they are directly applied to let-bindings or record fields (as demonstrated in the logger example above). They can neither be applied to function bodies, nor to separate type definitions:

RES
exception Abort let testExn: 'a. unit => 'a = () => raise(Abort) // Works! let testExn2 = (): 'a. 'a = raise(Abort) // Syntax error! type fn = 'a. 'a => unit // Syntax error!
Extensible VariantInterop Cheatsheet

© 2024 The ReScript Project

Software and assets distribution powered by KeyCDN.

About
  • Community
  • ReScript Association
Find us on