Course contentsShow
← TypeScript
Lesson 384 of 1,7969. Union TypesFree lesson

Union Type Syntax and Readability

How to format union types for clarity, including when to use parentheses and line breaks.

Union Type Syntax and Readability

You'll learn how to format union types so they're clear and maintainable, even as they grow complex.

Formatting for Clarity

Union types use the | operator to combine types. While string | number is simple, real-world unions can involve many types or complex shapes. How you format them dramatically affects readability.

For short unions, keep them inline:

let id: string | number;
let status: "pending" | "success" | "error";

For longer unions, use line breaks with each type on its own line:

type ApiResponse = 
  | { status: "success"; data: string }
  | { status: "error"; message: string }
  | { status: "loading" };

Notice the leading | on each line? This style makes adding or removing types easier and keeps everything aligned.

When to Use Parentheses

Parentheses group unions when combining them with other type operations:

type Result = (string | number)[];  // Array of strings OR numbers
type Callback = (value: string | number) => void;  // Function accepting string OR number

Without parentheses, string | number[] means "string OR array-of-numbers" — very different!

Think of It Like a Grocery List

A short list fits on one line: "milk, eggs, bread." But a longer list needs structure — one item per line with bullets. Union types work the same way: start simple, add structure when complexity grows.

Key Takeaway: Format short unions inline, but use line breaks with leading | symbols for multi-type unions. Always use parentheses when combining unions with arrays, functions, or other type constructs to make your intent crystal clear.