Skip to content

Commit 722470a

Browse files
authored
Merge pull request #318 from kevanstannard/syntax-lookup-polyvar
Syntax lookup: Polyvar
2 parents badf8d8 + ca37f1e commit 722470a

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

misc_docs/syntax/language_polyvar.mdx

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
---
2+
id: "polyvar"
3+
keywords: ["polymorphic", "variant", "polyvar"]
4+
name: "#value"
5+
summary: "This is a `polymorphic variant`."
6+
category: "languageconstructs"
7+
---
8+
9+
[Polymorphic variants](/docs/manual/latest/polymorphic-variant) (or _poly variants_) are the structurally typed equivalent of [variants](/docs/manual/latest/variant).
10+
11+
In comparison to nominally typed variants, their values don't require any explicit type definition, and are not coupled to any specific module. The compiler will infer the type on demand, and compare poly variants by their value, instead of their type name.
12+
13+
However, you can also describe a set of polymorphic variants with a type declaration, which can be useful to explicitly annotate function parameters and values. The most common format is the _closed poly variant_ type definition that looks like this: `type x = [ #value ]` (Note the extra `[]` around the poly variant constructors!).
14+
15+
### Example
16+
17+
<CodeTab labels={["ReScript", "JS Output"]}>
18+
19+
```res
20+
type status = [#Waiting | #Running | #Error(string)]
21+
22+
let status1: status = #Waiting
23+
let status2: status = #Error("Network error")
24+
```
25+
26+
```js
27+
var status1 = "Waiting";
28+
29+
var status2 = {
30+
NAME: "Error",
31+
VAL: "Network error",
32+
};
33+
```
34+
35+
</CodeTab>
36+
37+
### References
38+
39+
* [Polymorphic Variant](/docs/manual/latest/polymorphic-variant)

0 commit comments

Comments
 (0)