Skip to content

Commit 98ac195

Browse files
Add section about extensible variant types.
1 parent 8b7f79e commit 98ac195

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

data/sidebar_manual_latest.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@
3333
"unboxed",
3434
"reserved-keywords"
3535
],
36+
"Advanced Language Features": [
37+
"extensible-variant"
38+
],
3639
"JavaScript Interop": [
3740
"embed-raw-javascript",
3841
"shared-data-types",
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
---
2+
title: "Extensible Variant"
3+
description: "Extensible Variants in ReScript"
4+
canonical: "/docs/manual/latest/extensible-variant"
5+
---
6+
7+
# Extensible Variant Types
8+
9+
Variants can be made extensible by defining a type using `..` and adding new variant constructors using `+=`.
10+
11+
<CodeTab labels={["ReScript", "JS Output"]}>
12+
13+
```res example
14+
type t = ..
15+
16+
type t += Other
17+
18+
type t +=
19+
| Point(float, float)
20+
| Line(float, float, float, float)
21+
```
22+
```js
23+
var Caml_exceptions = require("./stdlib/caml_exceptions.js");
24+
25+
var Other = Caml_exceptions.create("Playground.Other");
26+
27+
var Point = Caml_exceptions.create("Playground.Point");
28+
29+
var Line = Caml_exceptions.create("Playground.Line");
30+
```
31+
32+
</CodeTab>
33+
34+
Pattern-matching is possible the same way as with normal variants but there is one caveat:
35+
With extensible variants, the possibility to check for exhaustiveness vanishes, you always need a default case `_` here.
36+
37+
38+
<CodeTab labels={["ReScript", "JS Output"]}>
39+
40+
41+
```res example
42+
let print = v =>
43+
switch v {
44+
| Point(x, y) => Js.log2("Point", (x, y))
45+
| Line(ax, ay, bx, by) => Js.log2("Line", (ax, ay, bx, by))
46+
| Other
47+
| _ => Js.log("Other")
48+
}
49+
```
50+
```js
51+
function print(v) {
52+
if (v.RE_EXN_ID === Point) {
53+
console.log("Point", [v._1, v._2]);
54+
} else if (v.RE_EXN_ID === Line) {
55+
console.log("Line", [v._1, v._2, v._3, v._4]);
56+
} else {
57+
console.log("Other");
58+
}
59+
}
60+
```
61+
62+
</CodeTab>

0 commit comments

Comments
 (0)