Skip to content

Latest commit

 

History

History
39 lines (27 loc) · 1.28 KB

language_polyvar.mdx

File metadata and controls

39 lines (27 loc) · 1.28 KB
id keywords name summary category
polyvar
polymorphic
variant
polyvar
#value
This is a `polymorphic variant`.
languageconstructs

Polymorphic variants (or poly variants) are the structurally typed equivalent of variants.

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.

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!).

Example

<CodeTab labels={["ReScript", "JS Output"]}>

type status = [#Waiting | #Running | #Error(string)]

let status1: status = #Waiting
let status2: status = #Error("Network error")
var status1 = "Waiting";

var status2 = {
  NAME: "Error",
  VAL: "Network error",
};

References