Aleph-Alpha/ts-rs

Exporting enum discriminants

alexwaeseperlman opened this issue · 3 comments

I would like to export a struct that looks like this

#[derive(Serialize, Deserialize, Debug, Clone, TS)]
#[ts(export)]
pub enum BuildStatus {
    Unqueued = -1,
    Queued = 0,
    Building = 1,
    BuildFailed = 2,
    TestGameFailed = 3,
}

into a format that looks like this:

export enum BuildStatus {
    Unqueued = -1,
    Queued = 0,
    Building = 1,
    BuildFailed = 2,
    TestGameFailed = 3,
}

This is what was generated:

export type BuildStatus = "Unqueued" | "Queued" | "BuildSucceeded" | "TestGameSucceeded" | "BuildFailed" | "TestGameFailed";

Is there a way to get an enum in typescript with the same discriminants as in rust?

I'm in need of this also

raine commented

I thought I would need this but it turned out that the enum values are serialized to their string representation when sent as JSON response from axum. So I can use the literal string representation in the TypeScript code, Rust enum in rust code, and in the database the enum is stored as an integer.

#[repr(i32)]
#[derive(Hash, Eq, Debug, PartialEq, sqlx::Type, TS, Serialize, Deserialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub enum MyEnum {
    Foo = 1,
    Bar = 2,
}

Duplicate of #23