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

Union Types in Function Parameters

Accept multiple types in function parameters using unions, requiring narrowing inside the function.

Union Types in Function Parameters

You'll learn: How to accept multiple different types as function parameters using unions, and why you'll need to narrow those types inside the function body.

The Core Idea

When you define a function parameter with a union type, TypeScript allows callers to pass any of those types. However, inside the function, you can only safely use operations that work on all the types in the union. To use type-specific operations, you must narrow the type first using techniques like typeof, truthiness checks, or other guards.

Think of it like a package delivery service that accepts both letters and boxes. At the receiving desk (function entry), you accept both. But to process them correctly, you need to check which one you received before using letter-specific or box-specific handling procedures.

Why This Matters

Without narrowing, TypeScript only lets you access properties and methods that exist on every type in the union. This prevents runtime errors when you assume the wrong type.

function formatValue(value: string | number) {
  // ❌ Error: toUpperCase doesn't exist on number
  // return value.toUpperCase();
  
  // ✅ Works: both types support this
  return String(value);
}

To use type-specific operations, you narrow:

function formatValue(value: string | number) {
  if (typeof value === "string") {
    // TypeScript knows value is string here
    return value.toUpperCase();
  } else {
    // TypeScript knows value is number here
    return value.toFixed(2);
  }
}

Key Takeaway: Union types in function parameters let you accept multiple types flexibly, but you must narrow the type inside the function to access type-specific properties or methods safely.