I had some joy moment when I realized that I could use different types of records with the same function if I pass an accessor. I thought I had to use objects as hinted in this doc
But then I tried the accessor pattern and it worked like a charm.
Variants are awesome, I just haven’t found a way to use Variants outside of another file.
For example if the Variant was declared in Utils.re, how can I use it in Button.re ?
In such situation the compiler can not infer the types so you’ve to open the module which has the type annotation to make the type available in scope or annotate expression explicitly.
// Util.re
type t = Foo | Bar;
// Button.re
let a: Util.t = Foo;
let f: Util.t => int =
x =>
switch (x) {
| Foo => 1
| Bar => 2
};
// open in module scope
open Util;
let a' = Foo;
let f' = x =>
switch (x) {
| Foo => 1
| Bar => 2
};
// or open locally (in expression)
let a'' = Util.(Foo);
let f'' = x =>
Util.(
switch (x) {
| Foo => 1
| Bar => 2
}
);
Thanks @chenglou
I did see the docs but missed the part of how to use Variants in multiple files. Now I see that I had to open the file with the variant or I can also use it like Variant Needs an Explicit Definition in the docs that @chenglou mentioned