ts-rs icon indicating copy to clipboard operation
ts-rs copied to clipboard

Export enum variants as distinct types

Open tbillington opened this issue 3 years ago • 2 comments

Hey I'm really enjoying using this library so far :)

Have you thought about providing the option to export enum variants as distinct types?

Say I have

#[derive(Serialize, Deserialize, Debug, TS)]
#[ts(export)]
pub enum Cmd {
    Process(u32),
    Stop(String),
}

it will produce

export type ServerCommand = 
    | { Process: number }
    | { Stop: string }

However, while TS can infer if I'm correctly constructing a ServerCommand, it would be helpful to be able to type specific variants.

So the result would end up something like this...

export type ServerCommand_Process = { Process: number };
export type ServerCommand_Stop = { Stop: string };
export type ServerCommand = 
    | ServerCommand_Process
    | ServerCommand_Stop;

tbillington avatar Feb 13 '22 03:02 tbillington

I explored a simple approach to implementing this:

Example:

#[derive(TS)]
#[ts(export, split, export_to = "tests-out/split_enum/")]
enum X {
    A(i32),
    B { x: i32, b: i32 },
}

In enum_def, we generate a type for each variant:

#[derive(ts_rs::TS)]
struct X_A(i32);

#[derive(ts_rs::TS)]
struct X_B {
    x: i32,
    b: i32,
}

and recursively call enum_def with this modified EnumItem:

#[ts(export, export_to = "tests-out/split_enum/")] 
enum X { A(X_A), B(X_B) }

NyxCode avatar Mar 01 '24 09:03 NyxCode

I like this approach as we have a few on our team that would prefer distinct types for rust enums - is there still a possibility of this becoming a feature?

Shearerbeard avatar Jan 31 '25 19:01 Shearerbeard