reasonml / reason

Simple, fast & type safe code that leverages the JavaScript & OCaml ecosystems
http://reasonml.github.io
MIT License
10.14k stars 428 forks source link

Better type inference for destructuring assignment #2627

Closed a-gierczak closed 3 months ago

a-gierczak commented 4 years ago

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
Lupus commented 4 years ago

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

bobzhang commented 3 years ago

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

anmonteiro commented 3 months ago

This is not a feature that we’ll support in Reason or Melange because it’s a breaking change from OCaml.

check https://github.com/melange-re/melange/pull/161 for some reasoning