Skip to main content

Archive

Show more

Union Types in TypeScript

Union Types in TypeScript

Union types in TypeScript allow a variable to hold more than one type of value. This is particularly useful when a variable can have multiple types of values at different times. Union types are created using the pipe (|) symbol between the types.


Basic Usage

Union types enable a variable to be assigned a value of multiple possible types. Here is an example of how to declare and use a union type:


let value: string | number;

value = "Hello";
console.log(value); // Output: Hello

value = 42;
console.log(value); // Output: 42

Union Types in Functions

Union types can be used in function parameters to accept multiple types of arguments:


function printValue(value: string | number) {
  console.log(value);
}

printValue("Hello"); // Output: Hello
printValue(42);      // Output: 42

Type Guards with Union Types

Type guards allow you to check the type of a value within a union type and perform specific operations based on that type:


function printLength(value: string | number) {
  if (typeof value === "string") {
    console.log(value.length); // string-specific property
  } else {
    console.log(value); // number
  }
}

printLength("Hello"); // Output: 5
printLength(42);      // Output: 42

Using Union Types with Arrays

Union types can also be applied to arrays, allowing an array to contain multiple types of elements:


let mixedArray: (string | number)[] = ["Alice", 30, "Bob", 25];

for (let value of mixedArray) {
  console.log(value);
}
// Output:
// Alice
// 30
// Bob
// 25

Union Types with Interfaces

Union types can be used with interfaces to create more flexible and comprehensive type definitions:


interface Dog {
  breed: string;
  bark: () => void;
}

interface Cat {
  breed: string;
  meow: () => void;
}

type Pet = Dog | Cat;

let pet: Pet = {
  breed: "Labrador",
  bark: () => console.log("Woof!")
};

console.log(pet.breed); // Output: Labrador
pet.bark();             // Output: Woof!

pet = {
  breed: "Siamese",
  meow: () => console.log("Meow!")
};

console.log(pet.breed); // Output: Siamese
pet.meow();             // Output: Meow!

Conclusion

Union types in TypeScript provide a powerful way to work with variables and function parameters that can hold multiple types of values. By using union types, you can write more flexible and reusable code while maintaining strong type safety. Understanding and using union types effectively can help you handle various scenarios where multiple types are required, making your TypeScript code more robust and adaptable.

Comments