Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Enums and Unions

typewriter fully supports Rust enums in all their forms.

Unit Enums

Simple enums with no data:

#![allow(unused)]
fn main() {
#[derive(TypeWriter)]
#[sync_to(typescript, python, go)]
pub enum Role {
    Admin,
    User,
    Guest,
}
}

TypeScript:

export type Role = "Admin" | "User" | "Guest";

Python:

class Role(str, Enum):
    ADMIN = "Admin"
    USER = "User"
    GUEST = "Guest"

Tuple Variants

Enums with unnamed fields:

#![allow(unused)]
fn main() {
#[derive(TypeWriter)]
#[sync_to(typescript)]
pub enum Result {
    Ok(String),
    Err { message: String },
}
}

TypeScript:

type Result =
    | { kind: "Ok"; value: string }
    | { kind: "Err"; message: string };

Struct Variants

Enums with named fields:

#![allow(unused)]
fn main() {
#[derive(TypeWriter)]
#[serde(tag = "type")]
#[sync_to(typescript)]
pub enum Event {
    Click { x: u32, y: u32 },
    KeyPress { key: String },
}
}

TypeScript:

type Event =
    | { type: "Click"; x: number; y: number }
    | { type: "KeyPress"; key: string };

Mixed Variants

#![allow(unused)]
fn main() {
#[derive(TypeWriter)]
#[serde(tag = "type")]
#[sync_to(typescript)]
pub enum Message {
    Text { content: String },
    Data(Vec<u8>),
    Empty,
}
}

TypeScript:

type Message =
    | { type: "Text"; content: string }
    | { type: "Data"; value: string }
    | { type: "Empty" };