essentials:union_types

14. Union Types — Expressing Multiple Valid Shapes With Clarity

Union types let us declare that
a value may take one of several specific types.
Instead of relying on documentation, comments, or guesswork,
the type system itself expresses the allowed shapes.

They reflect a broader shift in modern PHP:
uncertainty should be explicit, not implied.


1. What Union Types Are

A union type declares that a parameter, property, or return value may be one of several types:

function parse(int|string $value): string
{
    return (string) $value;
}

This is not “anything goes”.
It’s a closed set of allowed shapes.


2. Why Modern PHP Uses Them

Union types reduce:

  • ambiguous type hints
  • reliance on docblocks
  • runtime surprises
  • unclear method signatures
  • defensive type checking

They make the contract visible and honest.


3. The Mental Model

A union type is a small, intentional set of allowed shapes.

It’s not about flexibility.
It’s about clarity.

The key idea:
Use union types when
a value may legitimately take one of a few known forms.

Not many.
Not open‑ended.
Just a small, meaningful set.


4. A Simple Example

Without union types:

/**
 * @param int|string $id
 */
function load($id) { /* ... */ }

The type is hidden in a comment.
Easy to miss.
Easy to drift.

With union types:

function load(int|string $id) { /* ... */ }

The contract is visible.
The meaning is clear.


5. When to Use Union Types

Use union types when:

  • a value has a small set of valid shapes
  • the alternatives are meaningful
  • the contract is stable
  • we want clarity at the boundary
  • we want to avoid docblock drift

Union types shine in DTOs, controllers, and API boundaries.


6. When Not to Use Union Types

Avoid union types when:

  • he set of types is large or open‑ended
  • the alternatives have different meanings
  • the value should be normalized earlier
  • the union hides unclear design
  • the logic depends on which type is passed

Union types are for clear alternatives,
not loose flexibility
.


When AI Gets This Wrong

AI often uses union types to avoid making a design decision, adding string|int|array|null where only one type should exist. Sometimes it mixes incompatible shapes, or uses union types where normalization would be clearer.

Our mental model helps us see when a union expresses real meaning
— and when AI is using it to avoid clarity.


Summary

Union types let us express multiple valid shapes with clarity.
- They replace ambiguous docblocks,
- reduce uncertainty,
- and make contracts explicit.

Once we internalize this,
we can immediately see when AI‑generated code:

  • overuses union types
  • mixes incompatible shapes
  • uses unions to avoid design decisions
  • or misses opportunities to clarify meaning

Union types are a small feature
— but they teach us
how modern PHP wants to express uncertainty
with intention and structure
.


essentials/union_types.txt · Last modified: by editor