This Is How I Mastered TypeScript Like I’m 5 (And How You Can, Too!)(5)



This content originally appeared on DEV Community and was authored by Karandeep Singh

Today! We’re going to continue TypeScript learning like you’re a smart 5-year-old who loves to build things and asks “why?” (which is the best thing ever).

& yes “why?” is my way of learning.

I’ve divided this into 20 Chapters. and will go one by one and each will be of 2 – 3 min. of read.
This is a Continuation. if you have not read the Previous chapter – Chapter 4

This is Chapter ⓹ TS Mastering

🧩 Chapter 5: Union & Intersection Types – “OR” and “AND” Magic

(aka: “Mix and Match Your Types!”)

Imagine This:

You’re designing a costume box for a party:

  • Some kids can be either a pirate OR a ninja
  • Some want to be both at the same time! 🏴‍☠️➕🥷

TypeScript says:

“No problem. I’ve got you.”

🔀 Union Types (|) – OR this OR that

Use when something can be one of multiple types.

let value: string | number;

value = "hello"; // ✅
value = 123;     // ✅
value = true;    // ❌ Nope! Only string or number

This says:

“value can be a string OR a number”

🧪 Real Example:

function printId(id: string | number) {
  console.log("Your ID is:", id);
}

So you can call printId("ABC123") or printId(9) — both are fine!

But there’s a catch: when using union types, you need to be careful what methods you use:

id.toUpperCase(); // ❌ What if it's a number?

TS will say: “Hold up! Not every type in the union has that method.”

We’ll fix this later with Type Narrowing in Chapter 6 🕵

🔗 Intersection Types (&) – this AND that

Use when you want to combine multiple types into one.

type Person = { name: string };
type Coder = { knowsTS: boolean };

type TSDev = Person & Coder;

let dev: TSDev = {
  name: "Karandeep Singh",
  knowsTS: true,
};

This says:

“A TSDev is both a Person and a Coder.”

You’ve now learned how to mix and match types like a pro

If you enjoyed this and want to master TypeScript and other technologies, follow the series and drop a like!🤝

I’m a passionate software developer sharing the cool things I discover, hoping they help you level up on your coding journey.

How i created my own State Management Library : Rethinking State Management in React — From a Dev, for Developers.


This content originally appeared on DEV Community and was authored by Karandeep Singh