GyanMilega

๐Ÿ“˜ Day 3 โ€“ TypeScript: Union Types, Type Aliases & Enums

Author: Sagar Kudu
Sagar Kudu

TypeScript: Union Types, Type Aliases & Enums


๐Ÿš€ TypeScript Learning Journey โ€“ Day 3

Topic: Union Types, Type Aliases & Enums

Welcome back to the series! ๐Ÿ‘‹
On Day 1, we explored variables, arrays, and functions.
On Day 2, we leveled up with interfaces, optional fields, and readonly properties.

Now on Day 3, weโ€™re adding three new tools to our TypeScript toolbox:

  • Union Types

  • Type Aliases

  • Enums

These features may sound fancy, but they make your code much easier to manage in real-world projects. Letโ€™s break them down with simple examples.


๐Ÿ”— Union Types โ€“ โ€œEither this or thatโ€

A union type means a variable can accept more than one type.
Think of it like a train station where different trains can stop โ€” but only the ones you allow.

let value: string | number;

value = "Hello"; // โœ… works fine
value = 42;      // โœ… also works
// value = true; // โŒ not allowed

Functions also benefit from unions:

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

printId(101);      // ID: 101
printId("xyz123"); // ID: xyz123

๐Ÿ‘‰ Why is it useful?
When your program accepts more than one input type (e.g., ID as a number or string), you can enforce it clearly with unions.


๐Ÿท๏ธ Type Aliases โ€“ Giving Names to Types

If you keep repeating the same type, it becomes noisy.
A type alias is like giving a nickname to a type, so your code looks clean.

Example with a union:

type ID = string | number;

let userId: ID;
userId = 123;   // โœ… OK
userId = "abc"; // โœ… OK

For objects:

type Car = {
  brand: string;
  year: number;
};

const car1: Car = { brand: "Tata", year: 2025 };

๐Ÿ‘‰ When to use?

  • Use interfaces when youโ€™re describing the shape of an object.

  • Use type aliases for unions, intersections, or reusable type shortcuts.


๐ŸŽฏ Enums โ€“ Fixed Sets of Choices

Enums are great when you have a limited list of options.
Instead of random strings everywhere, you define them once and reuse them safely.

Example: Fuel Types

enum FuelType {
  Petrol,
  Diesel,
  Electric
}

const myCar = {
  brand: "Tesla",
  fuel: FuelType.Electric
};

console.log(myCar);
// { brand: 'Tesla', fuel: 2 }

By default, enums start at 0. But numbers can be confusing, so letโ€™s switch to string enums for clarity:

enum FuelType {
  Petrol = "PETROL",
  Diesel = "DIESEL",
  Electric = "ELECTRIC"
}

const car2 = { brand: "Tata", fuel: FuelType.Diesel };

console.log(car2);
// { brand: 'Tata', fuel: 'DIESEL' }

๐Ÿ‘‰ Why useful?

  • Prevents typos ("Petrol" vs "petroL")

  • Keeps your code consistent

  • Makes intent clear


๐Ÿ“ Exercises

  1. Union Type

type Status = "success" | "error";

function printStatus(status: Status) {
  console.log("Status:", status);
}

printStatus("success"); // Status: success
printStatus("error");   // Status: error

  1. Type Alias

type Point = { x: number; y: number };

const point1: Point = { x: 10, y: 20 };

console.log(point1);
// { x: 10, y: 20 }

  1. Enum

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT"
}

const move = Direction.Left;

console.log(move);
// LEFT

โœ… Recap

  • Union types allow multiple possible types.

  • Type aliases simplify code by giving names to types.

  • Enums handle fixed sets of choices safely.

These three concepts make your code less prone to errors and more readable.


๐Ÿ”ฎ Coming Up Next (Day 4)

On Day 4, weโ€™ll dive into Generics โ€” a powerful way to write flexible and reusable code without losing type safety.

Stay tuned โ€” this is where TypeScript starts to feel really powerful. ๐Ÿ’ช


๐ŸŽฏ Key Takeaways

  • Union types let variables hold a small set of possible types.

  • Type aliases make code cleaner by avoiding repetition.

  • Enums are the best choice when you have a fixed set of options.

With these, your TypeScript toolbox is growing โ€” and youโ€™ll see them everywhere in real-world projects.

Powered by wisp

Related Posts

๐Ÿ“˜ TypeScript: Day 2 โ€“ Interfaces & Object Types

Let us consider a previous example: const car: { brand: string; year: number } = { brand: "Tata", year: 2025 }; That works fine, but imagine you have lots of objects with the same shape. Typing { brand: string; year: number } again and again is messy. ๐Ÿ‘‰ This is where interfaces come in.

Read Full Story

๐Ÿ“˜TypeScript: Day 1 โ€“ Variables, Types & Functions

TypeScript: Variables, Types & Functions

Read Full Story

What is TypeScript?

TypeScript is a superset of JavaScript that adds static typing to the language. This means you can define the type of a variable, function parameter, or object property, allowing the compiler to catch type-related errors before your code runs. This leads to more robust and maintainable code.

Read Full Story

Why Do Front-End Frameworks Exist?

Modern frameworks like React, Vue, and Angular exist because building complex, interactive apps with just plain JavaScript quickly becomes unmanageable. Letโ€™s look at how web development evolved and why frameworks are the solution.

Read Full Story
Loading...
ยฉ Gyan Milega 2025