Skip to content

Add support to export enums as constant for TypeScript only #4464

Open
@ultraviolet-jordan

Description

@ultraviolet-jordan

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:

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

.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.

ExportJs::Expression(&format!("Object.freeze({{\n{}}})", variants)),

/**
 * @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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions