> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript Union Type

A union type is a composite type formed by combining two or more constituent types using the pipe operator (`|`). It declares that a value conforms to at least one of the specified types at compile time. Because TypeScript employs structural typing, a value may satisfy multiple constituent types simultaneously. Union types are strictly a compile-time construct and are erased during JavaScript emission, having no effect on runtime evaluation.

```typescript theme={"dark"}
type PrimitiveUnion = string | number | boolean;
```

## Property Access and Intersection

When a value is typed as a union, TypeScript restricts direct property access to the intersection of the constituents' properties. You can only invoke methods or access properties that are guaranteed to exist across *all* types within the union.

```typescript theme={"dark"}
interface Bird {
    fly(): void;
    layEggs(): void;
}

interface Fish {
    swim(): void;
    layEggs(): void;
}

declare const pet: Bird | Fish;

pet.layEggs(); // Valid: Shared across all constituents
// pet.fly();  // Error: Property 'fly' does not exist on type 'Bird | Fish'
```

## Type Narrowing

To access members specific to a single constituent type, the union must be narrowed. TypeScript utilizes control flow analysis in conjunction with type guards (such as `typeof`, `instanceof`, the `in` operator, or custom type predicates) to deduce the specific type within a given lexical scope.

```typescript theme={"dark"}
function processValue(val: string | number) {
    if (typeof val === "string") {
        // Control flow analysis narrows 'val' to string
        return val.toUpperCase(); 
    }
    // TypeScript infers 'val' is number in this branch
    return val.toFixed(2);
}
```

## Discriminated Unions and Exhaustiveness Checking

A discriminated union (often called a tagged union) is a structural pattern where every constituent type in the union shares a common literal property, known as the discriminant. TypeScript leverages this discriminant to perform deterministic type narrowing, typically within `switch` statements or `if/else` chains.

A primary mechanical benefit of discriminated unions is exhaustiveness checking. By assigning the unhandled cases to the `never` type in a `default` block, the compiler will enforce that all possible constituent types are evaluated. If a new type is later added to the union without updating the control flow, TypeScript will raise a compile-time error.

```typescript theme={"dark"}
interface Circle {
    kind: "circle"; // Discriminant property
    radius: number;
}

interface Square {
    kind: "square"; // Discriminant property
    sideLength: number;
}

type Shape = Circle | Square;

function calculateArea(shape: Shape) {
    switch (shape.kind) {
        case "circle":
            // TypeScript narrows 'shape' to Circle
            return Math.PI * shape.radius ** 2;
        case "square":
            // TypeScript narrows 'shape' to Square
            return shape.sideLength ** 2;
        default:
            // Exhaustiveness checking: ensures all 'kind' literals are handled.
            // If a 'Triangle' is added to 'Shape', this line causes a compiler error.
            const _exhaustiveCheck: never = shape;
            return _exhaustiveCheck;
    }
}
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor TypeScript Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
