Add support for representing enums as "const object"s#485
Add support for representing enums as "const object"s#485jthacker wants to merge 4 commits intoAleph-Alpha:mainfrom
Conversation
97c3975 to
64e0a1e
Compare
|
Hey @jthacker, thanks for the PR, I have a couple of questions:
|
39e8cbf to
f9dd66e
Compare
|
@gustavo-shigueo Thanks for the feedback! I've answered inline.
I wasn't aware of this feature, something I'm interested in using too. I have extended the
Yes, this is forbidden. This style only works with unit variants. The rust compiler will fail with an error like this
It works as expected. If you only want the type, you can import it with |
Goal
This PR introduces a new representation for enums:
#[ts(repr(enum = const_object))].While ts-rs already supports exporting enums as TypeScript enums or type unions, there are many cases where a TypeScript const object is preferred. This approach provides:
This is a common syntax used in modern TypeScript.
Additionally, as stated in the TypeScript docs the "biggest argument in favour of this format over TypeScript’s enum is that it keeps your codebase aligned with the state of JavaScript."
Changes
Macros
Repr::ConstObjectto theReprenum to support the new attribute.const_objectin#[ts(repr(enum = ...))].const_objectrepresentation in bothinline()anddecl(). This includes logic to handle implicit and explicit integer discriminants.const_objectrepresentation, ensuring it falls back to string names for unit variants without discriminants.Documentation
const_objectrepresentation, outlining its usage and requirements.Testing
rename_allstrategies (snake_case, camelCase, kebab-case).Other
cargo +nightly fmtas required by contributing guide resulting in many changes unrelated to this change so probably a gap in CIChecklist