reason icon indicating copy to clipboard operation
reason copied to clipboard

Better type inference for destructuring assignment

Open a-gierczak opened this issue 3 years ago • 2 comments

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

a-gierczak avatar Sep 04 '20 11:09 a-gierczak

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

Lupus avatar Sep 04 '20 20:09 Lupus

this was supported in latest releases of ReScript. Hence you get this for free if you are targeting web

bobzhang avatar Nov 10 '20 06:11 bobzhang