rescript-association / genType

Auto generation of idiomatic bindings between Reason and JavaScript: either vanilla or typed with TypeScript/FlowType.
https://rescript-lang.org/docs/gentype/latest/introduction
MIT License
758 stars 44 forks source link

Feature Request: Option to strip variants from single case variants. #559

Closed chrischen closed 3 years ago

chrischen commented 3 years ago

I posted this question on the ReScript forum: https://forum.rescript-lang.org/t/strip-variants-from-output/1766. I figure if such a feature doesn't exist then this is more of a feature for TS/Rescript interop.

Is there some way to strip variants from output, especially like from nested Records? If not, maybe this can be a useful feature?

// This causes type inference problems due to duplicated fields
type contact = { number: string, country: string };
type person = { name: string, contact: contact, country: string };

// One solution is to embed in modules
module Contact = {
  type t = { number: string, country: string };
}
module Person = {
  type t = { name: string, contact: Contact.t, country: string };
}

// However that can be syntactically heavy so I can use Variants to ensure unique Record types.
type contact = Contact({ number: string, country: string });
type person = Person({ name: string, contact: contact, country: string });

The output of person would have a Variant wrapping the contact field, and if using a record to interop with a JS Object the nested variants could be a big hassle in interop.

My reasoning here is to use Variants instead of modules for lightweight distinct record types. There may be some other cases where on the JS side I would just want the wrapped types for single-case variant types but would have to implement extra unwrapping code. This would allow for more natural usage of types in the Rescript side without having to add an additional interop conversion layer.

Currently if using modules to represent distinct types interop is smooth, but if I choose to use single case variants it makes it harder.

Is it possible to piggy back off of unboxed variant types for this?

Thoughts?

chrischen commented 3 years ago

Just tested this and adding [@ocaml.unboxed] does exactly this.