Nameof operator

Does ReScript have the concept of a nameof operator? Example in F#: Nameof - F# | Microsoft Learn

Something that can print the current value or field name of a symbol.

I’m my code I need to do something like:

type order = {
  isProcessed: bool,
  contact: contactPerson,
  created: milliseconds,
  tickets: array<ticket>,
  food: foodCount,
}

await orderSnapshot->update_field("isProcessed", true)

To update a single value in my Firebase database, I need to pass the name of my field as a string.
It would be great if I could do something like await orderSnapshot->update_field(nameof(isProcessed), true)

Does something like this exist?

There’s no such operator in rescript. You can build a runtime helper for this using proxy:

await orderSnapshot->update_field(o => o.isProcessed, true)

Where o is a proxy used to track which field is accessed. Also, this way, you can infer the value type.

1 Like

What would that proxy look like?

I’m talking about javascript proxy with get trap

So something along these lines:

const handler = {
  get: function (target, property, receiver) {
    return property;
  },
};

let nameof = (instance, getProperty) => {
  const p = new Proxy(instance, handler);
  return getProperty(p);
};

// Example property access
let y = { bar: 3 }
console.log(nameof(y, (y) => y.bar));

?

That’s very clever, had never thought of that.

I don’t remember the exact API. Looks like the code won’t work correctly, but this is what I meant :+1:

I like hacky solutions like this :joy:

2 Likes

This works for me: ReScript Playground

3 Likes