Akash Deep Vishwakarma
2 min readNov 13, 2023
Union Type in Typescript

πŸš€ Exciting TypeScript Journey: Unveiling the Power of Union Types! πŸš€

πŸ‘‹ Let’s dive into the TypeScript wonderland today and explore Union Types!

πŸ€” Imagine you have a variable that can be more than one type.

βš™οΈ What exactly are Union Types?

In a nutshell, they allow a variable to have multiple types, giving you the flexibility to handle various scenarios without compromising on type safety.

πŸ™„ How to represent Union Type?

In Typescript, we use | (OR) symbol for representing Union Type.

πŸ‘€ Have a look at this code -

type Result = string | number;
const handleResult = (result: Result) => {
// Now result can be a string or a number!
// TypeScript ensures we handle both cases gracefully.
};

😎 Why are they so cool?

πŸ‘‰ Versatility: Union Types let you handle a diverse set of inputs without resorting to β€˜any’ type.

πŸ‘‰ Readability: Code becomes more self-explanatory and readable, like a conversation with your code.

πŸ‘‰ API Responses: When your API can throw different types of responses, Union Types ensure you’re ready for any twist while running the application.

πŸ‘‰ Event Handling: Perfect for handling diverse events in an application.

πŸ’‘ Real-world Example:

Let’s say you’re working on a function that can accept either a string or an array.

πŸ’₯ Boom! Union Types make it effortlessly possible without compromising type safety.

function processData(data: string | string[]): void {
// Your logic here
}

πŸ•΅οΈβ€β™‚οΈ Type Guards to the Rescue:

πŸ‘‰ Dealing with Union Types also introduces us to the intriguing world of type guards.

πŸ‘‰ These nifty guards help TypeScript narrow down the actual type within the Union, making your code smarter and more reliable.

πŸ‘‰ Helpful in Type-checks at Runtime.

function processData(data: string | string[]): void {
if (typeof data === 'string') {
// Handle string case
} else {
// Handle array case
}
}

🚦 Combining Types for a Symphony:

Think of Union Types as musical notes. When combined correctly, they create a beautiful symphony in your code.

🎡 Let your creativity flow and compose elegant solutions!

Excited about Union Types?😁

Hit that β€˜Like’ button!❀️

Share your thoughts in the comments, and don’t forget to give this post a share to enlighten more minds in our tech community!πŸ”—

Akash Deep Vishwakarma
Akash Deep Vishwakarma

Written by Akash Deep Vishwakarma

Specialist Programmer (SDE) @ Infosys | Java | Kotlin | TypeScript | Angular | Spring | Spring Boot | Android Developer

Responses (1)