Syntax Lookup

Enter some language construct you want to know more about.

:>

This is the type coercion operator.

The :> operator may be used to convert a polymorphic variant to a string or int, or convert an object to a type with a subset of its fields.

Since ReScript 11.0.0 coercion also works for converting

  • from int to float

  • from record to record with the same field(s) or when record A is a subtype of record B

  • from @unboxed variant with only strings to string

  • from string to @unboxed variant that have a catch-all unboxed string case

  • from variant to variant when applicable

  • from variant to string/int/float when applicable

  • for invariant type arguments such as array payloads when the runtime representation is guaranteed to be exactly the same

Since ReScript 12, coercion also supports:

  • a closed polymorphic variant to a regular variant when all possible source constructors have matching target constructors

  • resolving type variables from the surrounding expression while checking the coercion

Example 1

ReScriptJS Output
type color = [#Red | #Green | #Blue]
let color: color = #Red
let message = "The color is " ++ (color :> string)

Example 2

ReScriptJS Output
type bit = [#0 | #1]
let bit: bit = #1
let value = (bit :> int)

Example 3

ReScriptJS Output
type person = {"id": int, "name": string}
type name = {"name": string}
let person = {"id": 10, "name": "Gideon"}
let name = (person :> name)

Example 4

ReScriptJS Output
@unboxed
type myNumberType = One | Two | Other(string)

let v = Other("Infinite")
let v2 = One

let x = "NaN"

// variant to string
Console.log((v :> string))
Console.log((v2 :> string))

// string to variant
let y = (x :> myNumberType)

let f = switch y {
| One => "One"
| _ => "Two"
}

Polymorphic Variant to Regular Variant

RES
type command = [#Start | #Stop] type event = Start | Stop | Pause let command: command = #Start let event: event = (command :> event)

Inferred Source Type

RES
type userId = private string let inspect = (_: userId) => () let unwrap = value => { inspect(value) (value :> string) }

The call to inspect determines the otherwise-unannotated value parameter's type, and the coercion is checked with that inferred type.

References