Export enum variants as distinct types
Opened this issue · 1 comments
tbillington commented
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 commented
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) }