Attribute (Decorator)
Like many other languages, ReScript allows annotating a piece of code to express extra functionality. Here's an example:
The @inline
annotation tells mode
's value to be inlined into its usage sites (see output). We call such annotation "attribute" (or "decorator" in JavaScript).
An attribute starts with @
and goes before the item it annotates. In the above example, it's hooked onto the let binding.
Usage
Note: In previous versions (< 8.3) all our interop related attributes started with a
bs.
prefix (bs.module
,bs.val
). Our formatter will automatically drop them in newer ReScript versions.
You can put an attribute almost anywhere. You can even add extra data to them by using them visually like a function call. Here are a few famous attributes (explained in other sections):
@@warning("-27")
@unboxed
type a = Name(string)
@val external message: string = "message"
type student = {
age: int,
@as("aria-label") ariaLabel: string,
}
@deprecated
let customDouble = foo => foo * 2
@deprecated("Use SomeOther.customTriple instead")
let customTriple = foo => foo * 3
@@warning("-27")
is a standalone attribute that annotates the entire file. Those attributes start with@@
. Here, it carries the data"-27"
.@unboxed
annotates the type definition.@val
annotates theexternal
statement.@as("aria-label")
annotates theariaLabel
record field.@deprecated
annotates thecustomDouble
expression. This shows a warning while compiling telling consumers to not rely on this method long-term.@deprecated("Use SomeOther.customTriple instead")
annotates thecustomTriple
expression with a string to describe the reason for deprecation.
Extension Point
There's a second category of attributes, called "extension points" (a remnant term of our early systems):
Extension points are attributes that don't annotate an item; they are the item. Usually they serve as placeholders for the compiler to implicitly substitute them with another item.
Extension points start with %
. A standalone extension point (akin to a standalone regular attribute) starts with %%
.