DEV Community

Cover image for Mastering TypeScript: Union Types & Type Aliases Explained
NJOKU SAMSON EBERE
NJOKU SAMSON EBERE

Posted on

Mastering TypeScript: Union Types & Type Aliases Explained

TypeScript offers powerful tools that help you write clean, scalable, and type-safe code. Two of the most useful features in this toolkit are Union Types and Type Aliases.

In my latest YouTube video, I break down how to use these features effectively—even if you're just getting started with TypeScript.

✅ What You'll Learn

  • ✅ What is a Union Type in TypeScript?
  • ✅ How to use Union Types with function parameters
  • ✅ What is a Type Alias and how to use it
  • ✅ How to combine Union Types and Aliases
  • ✅ Real-world use cases and code walkthroughs
  • ✅ Common mistakes to avoid

🔍 Why These Concepts Matter

If you've ever found yourself repeating types or making your code harder to read, Union Types let you define a variable that accepts multiple types:

let id: string | number;
Enter fullscreen mode Exit fullscreen mode

Meanwhile, Type Aliases allow you to give a custom name to a type:

type ID = string | number;

function printId(id: ID) {
  console.log("Your ID is:", id);
}
Enter fullscreen mode Exit fullscreen mode

Combined, they make your code more readable, reusable, and easier to maintain.


🧠 Real-World Example

type SuccessResponse = {
  status: "success";
  data: string;
};

type ErrorResponse = {
  status: "error";
  error: string;
};

type APIResponse = SuccessResponse | ErrorResponse;

function handleResponse(res: APIResponse) {
  if (res.status === "success") {
    console.log(res.data);
  } else {
    console.error(res.error);
  }
}
Enter fullscreen mode Exit fullscreen mode

This is a clean, scalable way to handle multiple response types from an API.


📺 Watch the Full Video

I walk you through all this and more in the full tutorial on YouTube:

👉 Watch on YouTube


💬 Final Thoughts

Whether you're building a small project or working with a large team, learning how to use Union Types and Type Aliases will make your TypeScript code more maintainable and developer-friendly.

If you find the video helpful, don’t forget to like, comment, and subscribe for more content like this!


Top comments (0)