Record Js output issue

I am using a variant structure to construct my Js objects.

My issue is that the Js output has the “TAG” field.

Is there a way to get a plain output?

I assume by ‘output’ you mean a one-way output? I.e., you don’t need to parse this output back into the original variant type? In that case you can write a function to convert the variant value into a JS object, e.g.

type number = string
type expiry = string
type code = string
type paymentMethod = Check | Card(number, expiry, code)

let toObject = paymentMethod =>
  switch paymentMethod {
  | Check =>
    {"type": "check"}
  | Card(number, expiry, code) =>
    {"type": "card", "number": number, "expiry": expiry, "code": code}
  }

Could you share the types you’ve defined?

Something like this is what I want to solve https://rescript-lang.org/try?code=PTAEAUBsFMEMGdqgHYHsAu0BcAoEoBaIvMAFQAskpYBPAcwCdUBXZAE1AEt5R51PIkULFAB3VAwDWXZKAAOTRtHjwSoAErQAygGMGnOelBhUkDpoSpZ8GsnSwAHr3Isz82A0SgAVsz5qAM05kJAAKOlRQdEj0SlAAIi1odH5kOnh49xChAIko1Do6SGC6Xlt7BwBKADoSNQAxaGgchib8+UhaYSZWDlh2UB1UAFs5ASR4Eeg1TV19Q0HUNmgAQhx0GjkkD3TQAF4cAEgAH1AAQQZ0gEZQgG9kWGHsXnR9NIBfSpxQE-PL+AATHdYHRnsF0J8cDgYEYAsgrvtQKEAPqVLDdXZ7AB8oFu3y4ASRr2Y0EquPxhwu1zu+NAPweT3R8W8qGg8QpkLp71AzS8eLplP+QP5dJ+IOeV1poE50pw7wA3DggA

This would raise a type error unless I am mistaken.

So the tag here is pretty essential so you can figure out which type of object you’re dealing with. It’s the same as typescript’s discriminated unions

Maybe you could talk more about your use-case and we can look if there’s alternatives?

Thanks,

My case is fairly straight forward, I want to be able to return either or.

let fn1 = (_) => {
  if (true) {
  	{
    	"name": "joe"
  	}
  } else {
  	{
    	"age": 1
    }
  }
};

Currently I am returning this as Js.Json.t which works as well for my case, but becomes less readability, more maintenance and plain weird when I need to include variable values.

Ah, in that case, @yawaramin 's solution is a good fit. When the keys are quoted in strings like demonstrated, it’s no longer a record, but a special ReScript object (not to be confused with OCaml objects). But this is more for JS interop - you don’t want to pass these things around in functions or anything like that

Yes, but unfortunately that is a noop :frowning: or am I missing the right type declarations?

Sorry, you are right. Here is a fixed version:

type number = string
type expiry = string
type code = string
type paymentMethod = Check | Card(number, expiry, code)

let toObject = paymentMethod =>
  switch paymentMethod {
  | Check =>
    {"type": "check", "number": None, "expiry": None, "code": None}
  | Card(number, expiry, code) =>
    {"type": "card", "number": Some(number), "expiry": Some(expiry), "code": Some(code)}
  }

Thanks, ofc, :slight_smile: :slight_smile: :slight_smile: