wasm-bindgen icon indicating copy to clipboard operation
wasm-bindgen copied to clipboard

Add support to export enums as constant for TypeScript only

Open ultraviolet-jordan opened this issue 8 months ago • 0 comments

Motivation

I want the ability for my enums in Rust to be exported to TypeScript as a constant.

Proposed Solution

A constant enum in TypeScript is like this:

export const enum Visibility {
  DEFAULT = 0,
  SOFT = 1,
  HARD = 2,
}

Which can be done as so:

https://github.com/rustwasm/wasm-bindgen/blob/c35cc9369d5e0dc418986f7811a0dd702fb33ef9/crates/cli-support/src/js/mod.rs#L4020

.push_str(&format!("export const enum {} {{", enum_.name));

However, today, some JS code is created since JS doesn't know what an enum is, and this feature would be TypeScript only.

https://github.com/rustwasm/wasm-bindgen/blob/c35cc9369d5e0dc418986f7811a0dd702fb33ef9/crates/cli-support/src/js/mod.rs#L4060

/**
 * @enum {0 | 1 | 2}
 */
module.exports.Visibility = Object.freeze({
    DEFAULT: 0, "0": "DEFAULT",
    SOFT: 1, "1": "SOFT",
    HARD: 2, "2": "HARD",
});

So this JavaScript code would no longer have to be generated. A constant enum is different from a regular enum in that the values get inlined at compile time from TypeScript to JavaScript. Regular enums are considered full objects otherwise. I think it completely makes sense for them to be this way since the way Rust works is basically enforced, the only real problem is keeping JavaScript support.

Maybe this would be like a feature flag to enable or something for TypeScript only use?

Alternatives

N/A

Additional Context

Add any other context or screenshots about the feature request here.

ultraviolet-jordan avatar Mar 24 '25 02:03 ultraviolet-jordan