ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Ts Union Types in TypeScript

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='19' AND `tutorial_submenu`='1158' AND `tutorial_status`=1 LIMIT 1

Ts Union Types in TypeScript

A union type in TypeScript allows a variable to hold one of several defined types. It provides flexibility while still maintaining type safety, making it especially useful for scenarios where a value can have multiple types.


Syntax

Union types are defined using the pipe (|) symbol between two or more types.

typescript

// value = true; // Error: Type 'boolean' is not assignable to type 'string | number'


Features of Union Types

  1. Type Safety
    TypeScript ensures that only the specified types are allowed.

  2. Flexibility
    Enables handling of values with varying types in a controlled manner.

  3. Type Narrowing
    Use type guards to determine the specific type of a union variable.


Examples of Union Types

1. Basic Union Type

typescript

let data: number | string;data = 10; // Validdata = "Ten"; // Valid

2. Union in Function Parameters

typescript

function printValue(value: string | number): printValue(42); // Output: 42


Type Guards

TypeScript allows you to narrow down the type of a union variable using conditional checks.

Using typeof

typescript

function processValue(value: string | number): void { if (typeof value === "string") { console.log(value.toUpperCase()); // Works because 'value' is narrowed to string } else { console.log(value.toFixed(2)); // Works because 'value' is narrowed to number }}

Using instanceof

typescript

class Dog { bark() { console.log("Woof!"); }}class Cat { meow() { console.log("Meow!"); }}function handlePet(pet: Dog | Cat): void { if (pet instanceof Dog) { pet.bark(); } else { pet.meow(); }}


Union with Arrays

Union types can be used for arrays to allow elements of different types.

typescript

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

Union with Literal Types

Union types can include literal values for more specific constraints.

typescript

type Direction = "up" | "down" | "left" | "right";function move(direction: Direction): void { console.log(`Moving ${direction}`);}move("up"); // Valid// move("forward"); // Error: Type '"forward"' is not assignable to type 'Direction'


Union with Null or Undefined

Union types are commonly used to handle null or undefined values, especially when strictNullChecks is enabled.

typescript

let name: string | null = null;name = "Alice"; // Valid


Advantages of Union Types

  1. Improves Code Flexibility
    Handles multiple input types in a single variable or parameter.

  2. Enhances Code Safety
    Prevents runtime errors by enforcing compile-time checks for allowed types.

  3. Clearer Code Intentions
    Makes it explicit that a variable or parameter can have more than one type.


Common Use Cases

  1. Function Overloads

    typescript

    function getLength(value: string | string[]): number { return typeof value === "string" ? value.length : value.length;}

  2. Error Handling

    typescript

    type Response = { success: true; data: string } | { success: false; error: string };function handleResponse(response: Response): void { if (response.success) { console.log("Data:", response.data); } else { console.error("Error:", response.error); }}

  3. API Parameters

    typescript

    type ID = number | string;function fetchUser(id: ID): void { console.log(`Fetching user with ID: ${id}`);}


Best Practices

  1. Use Type Guards for Narrowing
    Always check the specific type before performing type-specific operations.

  2. Combine with Aliases
    Use type aliases to simplify complex union types.

    typescript

    type Input = string | number;

  3. Avoid Overuse
    If a union becomes too complex, consider refactoring with interfaces or discriminated unions.


Conclusion

Union types are a powerful feature in TypeScript that allow for flexible yet type-safe handling of variables with multiple possible types. By leveraging union types effectively, you can write robust and maintainable code.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql