Data shapes · 11 min · free lesson

TypeScript unions vs enums

A TypeScript discriminated union becomes a Rust enum whose variants carry their own data, and match must handle every variant.

Core idea

An enum variant carries its own data, and match must cover every variant; a guard narrows an arm but never excuses a missing case.

TypeScript and Rust, side by side

TypeScript A string tag narrows the union; the never default is TypeScript's opt-in exhaustiveness check.
type Payment =
  | { kind: "card"; last4: string }
  | { kind: "transfer"; reference: string }
  | { kind: "cash" };

function describe(p: Payment, cents: number): string {
  switch (p.kind) {
    case "card":
      return `card ending ${p.last4}`;
    case "transfer":
      return `transfer ${p.reference}`;
    case "cash":
      return cents > 50_000 ? "cash, needs approval" : "cash";
    default: {
      const unhandled: never = p; // compile error if a kind is added
      return unhandled;
    }
  }
}

console.log(describe({ kind: "card", last4: "4242" }, 900));
console.log(describe({ kind: "cash" }, 60_000));
Rust Each arm destructures its variant, and the guarded Cash arm is followed by an unguarded one.
enum Payment {
    Card { last4: String },
    Transfer { reference: String },
    Cash,
}

fn describe(p: &Payment, cents: u32) -> String {
    match p {
        Payment::Card { last4 } => format!("card ending {last4}"),
        Payment::Transfer { reference } => format!("transfer {reference}"),
        Payment::Cash if cents > 50_000 => String::from("cash, needs approval"),
        Payment::Cash => String::from("cash"),
    }
}

fn main() {
    let card = Payment::Card { last4: String::from("4242") };
    let transfer = Payment::Transfer { reference: String::from("INV-7") };
    println!("{}", describe(&card, 900));
    println!("{}", describe(&Payment::Cash, 60_000));
    println!("{}", describe(&transfer, 100));
}
What changes
TypeScriptRust
{ kind: "card"; last4: string } uses a string tag.Card { last4: String }: the variant is the tag, and the compiler checks it.
Exhaustiveness needs const unhandled: never = p in default.Every match is checked; a missing variant is E0004.
JSON at runtime can carry any kind despite the type.A Payment can only be one of its variants; outside data must be parsed into one first.
case "cash": return cents > 50_000 ? ... : ...Payment::Cash if cents > 50_000 => is a guard; a plain Payment::Cash => arm must follow.

Understand it

A discriminated union is a set of object shapes sharing a tag such as kind, narrowed by a switch. Rust builds the same idea into the type system: enum Payment { Card { last4: String }, Transfer { reference: String }, Cash }. The variant is the tag. There is no string field to misspell, and data that belongs to one variant cannot be read through another.

match replaces the switch plus the never trick. TypeScript checks exhaustiveness only if you add a default with const unhandled: never, and only at compile time: at runtime a value from JSON can still carry an unknown kind. Rust's match must cover every variant or the program does not compile (E0004), and a value of type Payment cannot hold anything else, because outside data has to be parsed into a variant first.

Patterns destructure while they match. Payment::Card { last4 } => binds the field, and a literal field such as Shipped { days: 0, .. } matches one specific value. A guard, Payment::Cash if cents > 50_000 =>, adds a condition; when it is false, matching continues with the next arm. Guards do not count toward exhaustiveness, so a plain Payment::Cash => arm must still follow.

Be careful with _. A wildcard arm silences E0004 for every variant added later, which is exactly the check you came for. In code that should be revisited whenever the enum grows, list the variants explicitly.

The TypeScript habit, written in Rust

This is how the TypeScript version usually looks on a first attempt in Rust. Predict what rustc says before you read the explanation.

enum Payment {
    Card,
    Transfer,
    Cash,
}

fn fee(p: Payment) -> u32 {
    match p {
        Payment::Card => 30,
        Payment::Transfer => 0,
    }
}

fn main() {
    println!("{}", fee(Payment::Cash));
}

Practise this code in Playground ↗

Try it

Port the TypeScript eta shown at the top of solution.rs; the Shipment enum is given. Return not shipped yet, arrives today via <carrier> for 0 days, 1 day via <carrier>, <n> days via <carrier>, delivered and lost. Cover every variant without a _ arm. In the Crabrix app, open the compiler lab and complete the supplied function in solution.rs. The reading question is a separate exercise.

What success looks like: The local compiler accepts the changed solution and the separate verification harness passes every variant, including 0 and 1 days. Printing a success message alone does not complete this lab.

Check your understanding

A match on Payment ends with _ => 0. Later someone adds Payment::Crypto. What happens?

Reveal the answer
  1. rustc reports E0004 for the new variant
  2. The program panics when Crypto reaches the match
  3. It compiles, and Crypto silently takes the wildcard arm

A wildcard covers every variant, including future ones, so the compiler has nothing to report. List the variants where a new one should force a review.

Go deeper

Common misconception: “A _ => arm is the safe default, like default: in a switch.”

A wildcard turns off the exhaustiveness check for every variant added later; in TypeScript terms it deletes the never check. List the variants unless the fallback is really meant for future cases too.

  1. Read the variants: Card and Transfer each carry a String, and Cash carries nothing. The amount is a separate parameter.
  2. Order the arms: The guarded Payment::Cash if cents > 50_000 arm comes before the plain Payment::Cash arm. In the other order the guarded arm could never match, and rustc warns that it is unreachable.
  3. Compare with evidence: Run it: card ending 4242, cash, needs approval, transfer INV-7. Delete the plain Cash arm and read E0004: the guard does not cover Cash.

Transfer challenge: Add a Voucher { code: String } variant and compile before you touch describe. Then return voucher <code> for it, and use a guard to reject a voucher whose code is empty.

Connections

  • Classes and objects vs structs: Data in structs, behaviour in impl blocks
  • null, undefined and ?? vs Option: Absence as Option<T>
Side-by-side comparison: the TypeScript version on the left, the Rust version on the right, then 4 rows naming what changes.
TypeScript unions vs enums: the same task in TypeScript and in Rust, with the differences that matter.
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: TypeScript unions vs enums (courseId "rust-for-nodejs-developers", lessonId "node-ts-unions-to-enums")
Link: https://crabrix.com/learn/rust-for-nodejs-developers/node-ts-unions-to-enums/
Goal: An enum variant carries its own data, and match must cover every variant; a guard narrows an arm but never excuses a missing case.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-nodejs-developers/node-ts-unions-to-enums) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.