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

Export enum variants as distinct types #86

Open
tbillington opened this issue Feb 13, 2022 · 1 comment
Open

Export enum variants as distinct types #86

tbillington opened this issue Feb 13, 2022 · 1 comment
Labels
enhancement New feature or request

Comments

@tbillington
Copy link

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;
@NyxCode
Copy link
Collaborator

NyxCode commented Mar 1, 2024

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) }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants