Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add enums to the HybridObject #7

Merged
merged 3 commits into from
Feb 22, 2024
Merged

feat: Add enums to the HybridObject #7

merged 3 commits into from
Feb 22, 2024

Conversation

mrousavy
Copy link
Member

Adds support for enums to HybridObject:

When declaring custom enums there's two steps you need to do:

  1. Create your enum (e.g. in TestEnum.h)
enum TestEnum {
    FIRST,
    SECOND,
    THIRD
};
  1. Add the enum to the EnumMapper by editing cpp/jsi/EnumMapper.h:
template<>
struct EnumMapper<TestEnum> {
public:
    static constexpr TestEnum fromJSUnion(const std::string& jsUnion) {
        if (jsUnion == "first") return FIRST;
        if (jsUnion == "second") return SECOND;
        if (jsUnion == "third") return THIRD;
        throw invalidUnion(jsUnion);
    }
    static std::string toJSUnion(TestEnum value) {
        switch (value) {
            case FIRST: return "first";
            case SECOND: return "second";
            case THIRD: return "third";
        }
        throw invalidEnum(value);
    }
};

This way compile-time safety is guaranteed.

All other approaches to parse enums from C++ to JS are not compile-time but rather run-time, so currently there's no way around editing EnumMapper.h unless we do runtime type checking.

@mrousavy mrousavy merged commit ba2313a into main Feb 22, 2024
4 of 5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant