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

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"
}

References