reason
reason copied to clipboard
Better type inference for destructuring assignment
As far as I understand OCaml's type inference works top-bottom, left-right so it somewhat makes sense that when destructuring a record it guesses the type by record field names on the left hand side of the assignment. However when type of the record is already known it's counterintuitive. Look at this example:
type person = {
name: string,
};
type animal = {
name: option(string),
};
let getName = (person: person): string => {
let {name} = person;
name;
};
Despite that type of person is already known, compiler still tries to infer the type (and does it wrong), which results in compile error.
We've found a bug for you!
OCaml preview 5:49-54
This has type:
person
But somewhere wanted:
animal
Reason is an alternate syntax for OCaml, and the way record disambiguation works in OCaml is by matching record field names. That produces a Hindley-Milner constraint on the record type for {name}
, which later conflicts with constraints on person
, which is what reported to you by the type checker.
More info here: https://ocaml.org/manual/coreexamples.html#ss:record-and-variant-disambiguation
this was supported in latest releases of ReScript. Hence you get this for free if you are targeting web