Syntax Lookup

Enter some language construct you want to know more about.
This is the @as decorator.

The @as decorator has multiple uses in ReScript.

Change runtime name of record field

The @as decorator can be used on record types to alias record field names to a different JavaScript attribute name.

This is useful to map to JavaScript attribute names that cannot be expressed in ReScript (such as keywords).

It is also possible to map a ReScript record to a JavaScript array by passing indices to the @as decorator.

Examples

ReScriptJS Output
type action = {
  @as("type") type_: string
}

let action = {type_: "ADD_USER"}
ReScriptJS Output
type t = {
  @as("0") foo: int,
  @as("1") bar: string,
}

let value = {foo: 7, bar: "baz"}

Change the runtime representation of a variant constructor

Similarily to changing the runtime name of a record field, you can change the runtime representation of a variant constructor using @as(). Only with variants, you have many more options for the runtime representation than for record field names:

ReScriptJS Output
@unboxed
type pet = | @as("dog") Dog | @as(1) Cat | @as(null) SomethingElse

let dog = Dog
let cat = Cat
let somethingElse = SomethingElse

Read more about the @as decorator and variants.

Adding fixed argument values to external functions

You can leverage the @as decorator to add fixed values for external function arguments. You then do not need to supply a value for that argument.

ReScriptJS Output
@module("fs")
external readFileSyncUtf8: (string, @as(json`{encoding: "utf8"}`) _) => string = "readFileSync"

let contents = readFileSyncUtf8("./someFile.txt")

Read more about fixed arguments in functions.

References