LibraryUnion types

Union types

Learn about Union types as part of TypeScript Full-Stack Development

Mastering Union Types in TypeScript

Union types are a fundamental concept in TypeScript that allow a variable, parameter, or return value to accept one of several possible types. This feature significantly enhances type safety and flexibility in your code, especially in full-stack development where data can come from various sources and take different forms.

What are Union Types?

A union type is created by using the pipe symbol (

code
|
) between two or more types. It signifies that a value can be of any of the types listed in the union. This is incredibly useful when dealing with data that might be a string or a number, a specific set of string literals, or even a custom object with varying structures.

What symbol is used to define a union type in TypeScript?

The pipe symbol (|).

Practical Applications in Full-Stack Development

In full-stack development, you often encounter situations where data can have multiple forms. For instance, an API response might return a user ID as either a string or a number, or a status message could be a specific string literal like 'success', 'error', or 'pending'.

Consider a function that processes user input. This input might be a string from a text field or a number from a numerical input. Using union types, you can define the parameter to accept both:

function processInput(input: string | number) {
  if (typeof input === 'string') {
    console.log(`Processing string: ${input.toUpperCase()}`);
  } else {
    console.log(`Processing number: ${input.toFixed(2)}`);
  }
}

processInput('hello'); // Output: Processing string: HELLO
processInput(123.456); // Output: Processing number: 123.46

This code snippet demonstrates how a single function processInput can gracefully handle both string and number types. The typeof type guard is crucial here, allowing TypeScript to narrow down the type within the conditional blocks, enabling access to type-specific methods like .toUpperCase() for strings and .toFixed() for numbers. This prevents runtime errors and makes your code more robust.

📚

Text-based content

Library pages focus on text content

Working with Union Types: Type Narrowing

When you have a variable of a union type, TypeScript doesn't automatically know which specific type it currently holds. To safely access properties or methods unique to one of the types in the union, you need to use type guards. Common type guards include

code
typeof
,
code
instanceof
, and checking for the existence of specific properties.

Type guards are essential for safely working with union types, allowing you to 'narrow down' the type within a specific code block.

Union Types with Objects

Union types are also powerful when dealing with objects that might have different shapes. For example, a response from a backend might be a

code
User
object or an
code
Error
object.

Let's define interfaces for these possibilities:

typescript
interface User {
id: number;
name: string;
}
interface Error {
code: number;
message: string;
}
type ApiResponse = User | Error;
function handleResponse(response: ApiResponse) {
if ('id' in response) {
// TypeScript knows 'response' is a User here
console.log(`User ID: ${response.id}, Name: ${response.name}`);
} else {
// TypeScript knows 'response' is an Error here
console.log(`Error Code: ${response.code}, Message: ${response.message}`);
}
}
What type guard can be used to differentiate between object types in a union?

Checking for the existence of a specific property using the in operator (e.g., 'propertyName' in object).

Key Takeaways

Union types provide a flexible way to define variables that can hold values of multiple types. They are essential for writing robust and type-safe code in full-stack TypeScript applications. Remember to use type guards to safely access members of union types.

Learning Resources

TypeScript Official Handbook: Union Types(documentation)

The definitive guide from the TypeScript team on how union types work, including syntax and common use cases.

TypeScript Union Types Explained with Examples(blog)

A practical blog post that breaks down union types with clear, relatable examples for developers.

Understanding TypeScript's Type Guards(documentation)

Essential reading for using union types effectively, this page details various type guarding techniques.

TypeScript Union Types Tutorial - YouTube(video)

A visual explanation of union types in TypeScript, demonstrating their application and benefits.

Advanced TypeScript: Union Types and Intersection Types(blog)

This tutorial covers union types alongside intersection types, providing a broader context for type composition.

TypeScript Union Types - A Deep Dive(blog)

A comprehensive article exploring the nuances of union types, including their use with literals and complex data structures.

TypeScript Type Narrowing with `typeof` and `instanceof`(blog)

Focuses on the practical application of type guards, which are critical for working with union types.

TypeScript Union Types for API Responses(blog)

A specific example of how union types are beneficial when handling diverse API response structures in web development.

TypeScript Union Types - Learn with Examples(tutorial)

A step-by-step tutorial with code examples to help understand the creation and usage of union types.

TypeScript Union Types vs. Intersection Types(blog)

Compares and contrasts union types with intersection types, highlighting their distinct use cases in TypeScript.