Array access is sometimes option

Hi, when I access an array with arr[0] sometimes it returns the element, and sometimes it returns a type option on the element, and I have to call Option.getExn(), why?

Hi @fccm I think you might have opened Belt

module WithBelt = {
  open Belt
  let a = [1, 2, 3]

  //type of b is option<int>
  let b = a[0]

module WithoutBelt = {
  let a = [1, 2, 3]

  //type of b is int
  let b = a[0]



Indeed, I didn’t notice this trick :slight_smile:

Here’s a further explanation in the docs about this behavior.

I have also been away from rescript for a very long time (since March 2020) and just found this discussion topic while trying to track down some errors when updating my code.

When I cloned rescript-project-template today (August 2023) and entered this code into Demo.res:

let data = [100, 101, 102];
let n = data[0];
if (n == 100) {
} else {

I get this error:

  1 │ let data = [100, 101, 102];
  2 │ let n = data[0];
  3 │ if (n == 100) {
  4 │    Js.Console.log("yes");
  5 │ } else {

  This has type: int
  Somewhere wanted: option<int>

but I have not explicitly opened Belt anywhere. What am I missing here?

ReScript Core is likely opened, and in that array access is option.


Where would that have happened (it isn’t in the code I wrote–the code I pasted is the entire code in Demo.res) and how do I turn it off?

It’s in the bsconfig:

   "bsc-flags": [
-    "-open RescriptCore",

See also the ReScript-Core Readme.

Thanks. Now I have to decide whether I want to go with core or not.

1 Like