Mastering Union Types in TypeScript: A Complete Guide

Mastering Union Types in TypeScript: A Complete Guide

ยท

3 min read

Introduction

  • Imagine a world where your variables can hold multiple types of values, and you still have complete control over them.

  • Welcome to the world of Union Types in TypeScript!

  • This guide will take you on a journey to understand how Union Types can make your code more flexible and robust.

  • Get ready for an exciting dive into the versatile world of TypeScript's Union Types with real-life examples and practical code snippets.

What are Union Types?

  • Union Types allow a variable to hold more than one type.

  • This is incredibly useful when a value can be of different types at different times.

  • It enhances flexibility while maintaining type safety.

Declaring Union Types

You can declare a Union Type using the pipe (|) symbol between the types.

let value: number | string;
value = 42;    // Valid
value = "Hello";  // Valid

Real-Life Example: User Input

Consider a scenario where you need to handle user input that can be either a string or a number, such as an age or a name in a form.

function printInput(input: number | string) {
  if (typeof input === "string") {
    console.log(`You entered a string: ${input.toUpperCase()}`);
  } else {
    console.log(`You entered a number: ${input.toFixed(2)}`);
  }
}

printInput("John Doe");   // Output: You entered a string: JOHN DOE
printInput(25);           // Output: You entered a number: 25.00

Working with Union Types

Type Guards

Type Guards are used to narrow down the type within a Union Type during runtime. This allows you to perform type-specific operations safely.

function getLength(input: number | string): number {
  if (typeof input === "string") {
    return input.length;  // String-specific operation
  } else {
    return input.toString().length;  // Number-specific operation
  }
}

console.log(getLength("TypeScript"));  // Output: 10
console.log(getLength(12345));         // Output: 5

Union Types with Arrays

You can also use Union Types with arrays, making them even more powerful.

let mixedArray: (number | string)[] = [1, "two", 3, "four"];
mixedArray.push(5);
mixedArray.push("six");

console.log(mixedArray);  // Output: [1, "two", 3, "four", 5, "six"]

Advanced Usage: Function Overloading

Function overloading allows you to define multiple signatures for a function, enabling more precise type checking.

function combine(a: number, b: number): number;
function combine(a: string, b: string): string;
function combine(a: number | string, b: number | string): number | string {
  if (typeof a === "number" && typeof b === "number") {
    return a + b;  // Number-specific addition
  } else if (typeof a === "string" && typeof b === "string") {
    return a + b;  // String-specific concatenation
  } else {
    throw new Error("Invalid input types");
  }
}

console.log(combine(1, 2));           // Output: 3
console.log(combine("Hello, ", "World!"));  // Output: Hello, World!

Conclusion

  • Union Types in TypeScript provide the perfect balance between flexibility and type safety, allowing you to write more versatile and robust code.

  • By understanding and utilising Union Types, you can handle a wider range of scenarios with ease.

  • Start integrating Union Types into your TypeScript projects and experience the benefits firsthand!

Thank You Everyone For The Read ....

Happy Coding! ๐Ÿคž๐Ÿ’ป


๐Ÿ‘‹ Hello, I'm Aaryan Bajaj .

๐Ÿฅฐ If you liked this article, consider sharing it.

๐Ÿ”— X | LinkedIn

ย