Sitemap
The 60-Second Programmer

Quick, actionable programming tips and insights delivered in just 60 seconds. Perfect for developers who want to learn on the go. Whether you’re a beginner or seasoned pro, our bite-sized lessons fit your schedule and boost your coding skills fast!

Union & Literal Types 🔀

Model ‘one of these exact values’ precisely.

1 min read2 days ago

--

A union (|) says a value is one of several types. A literal type narrows it to one exact value. Together they're TypeScript's superpower.

Literal types

Instead of string, accept only specific strings:

type Direction = "up" | "down" | "left" | "right";
function move(d: Direction) { /* ... */ }move("up");   // ok
move("north"); // error: not a Direction

Narrowing

TypeScript narrows the type as you check it:

type Status = "loading" | "success" | "error";
function render(s: Status) {
if (s === "error") {
// s is "error" here
return "Something broke";
}
return s; // s is "loading" | "success"
}

Combine with switch for exhaustive handling — every case covered, compiler-verified.

Get Marcelo Domingues’s stories in your inbox

Join Medium for free to get updates from this writer.

TL;DR: Unions + literals replace loose string/number with a precise set of allowed values.

Swap a stringly-typed parameter for a literal union and watch the bugs vanish.

--

--

Written by Marcelo Domingues

🚀 Lead Software Engineer for Siemens | Crafting Code & Words | Empowering Tech Enthusiasts ✨ 📲 LinkedIn: https://www.linkedin.com/in/marcelogdomingues/

Published in The 60-Second Programmer

Quick, actionable programming tips and insights delivered in just 60 seconds. Perfect for developers who want to learn on the go. Whether you’re a beginner or seasoned pro, our bite-sized lessons fit your schedule and boost your coding skills fast!