KoderSolution Logo
HomeArticlesTutorialsForumAI LabRun Code
KoderSolution Logo

The world’s most advanced technical ecosystem for modern software engineers. Learn, build, and grow with next-generation developer tools and resources.

Engineering Newsletter

Join 100,000+ engineers receiving curated high-signal content weekly.

Platforms

  • Technical Articles
  • Interactive Tutorials
  • AI Coding Lab
  • Developer Forum
  • Developer Tools

Pages

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of Service
  • Refund Policy
  • Disclaimer
  • Advertisement

Popular Topics

  • PHP
  • Laravel
  • Python
  • React.Js
  • MySQL
© 2026 KoderSolutionAll Rights Reserved
Developed Bymaksudur.dev
🔷

TypeScript

Topic Hub & Articles

TypeScript Intro

10 min

TypeScript Getting Started

10 min

TypeScript Simple Types

10 min

TypeScript Explicit & Inference

10 min

TypeScript Special Types

10 min

TypeScript Arrays

10 min

TypeScript Tuples

10 min

TypeScript Object Types

10 min

TypeScript Enums

10 min

TypeScript Aliases & Interfaces

10 min

TypeScript Union Types

10 min

TypeScript Functions

10 min

TypeScript Casting

10 min

TypeScript Classes

10 min

TypeScript Basic Generics

10 min

TypeScript Utility Types

10 min

TypeScript Keyof

10 min

TypeScript Null & Undefined

10 min

TypeScript Definitely Typed

10 min

TypeScript 5 Updates

10 min

TypeScript Configuration

10 min

TypeScript Tooling

10 min

TypeScript Advanced Types

10 min

TypeScript Type Guards

10 min

TypeScript Conditional Types

10 min

TypeScript Mapped Types

10 min

TypeScript Type Inference

10 min

TypeScript Literal Types

10 min

TypeScript Namespaces

10 min

TypeScript Index Signatures

10 min

TypeScript Declaration Merging

10 min

TypeScript with Node.js

10 min

TypeScript with React

10 min

TypeScript Async Programming

10 min

TypeScript Decorators

10 min

TypeScript in JS Projects

10 min

TypeScript Migration

10 min

TypeScript Error Handling

10 min

TypeScript Best Practices

10 min

Progress
0%

0 / 39 Lessons

TypeScriptTypeScript Types
Lesson

TypeScript Union Types

10 min reading
Free Course

TypeScript Union Types: Flexible Types & Type Narrowing

A union type describes a value that can be one of several types, specified using the vertical bar (|) operator.

Type Narrowing Architecture

When working with union types, TypeScript requires you to narrow the broad union down to a specific type before calling type-specific methods.

flowchart TD
    A["Input: string | number"] --> B{"typeof value == 'string'?"}
    B -- "True" --> C["Branch: value.toUpperCase() (String Methods Available)"]
    B -- "False" --> D["Branch: value.toFixed(2) (Number Methods Available)"]

Practical Code Example

// Basic Union Type
type ResultId = string | number;

function formatIdentifier(id: ResultId): string {
  if (typeof id === "string") {
    // TypeScript automatically narrows id to string inside this block
    return `ID-STR-${id.toUpperCase()}`;
  } else {
    // TypeScript automatically narrows id to number inside this block
    return `ID-NUM-${id.toFixed(0)}`;
  }
}

// Discriminated Union (Tagged Union Pattern)
interface SuccessResponse {
  kind: "success";
  data: string[];
}

interface ErrorResponse {
  kind: "error";
  errorMessage: string;
}

type ApiResponse = SuccessResponse | ErrorResponse;

function handleApiResponse(response: ApiResponse): void {
  // Narrowing based on the discriminant 'kind' property
  if (response.kind === "success") {
    console.log(`Fetched ${response.data.length} records.`);
  } else {
    console.error(`API Failure: ${response.errorMessage}`);
  }
}

handleApiResponse({ kind: "success", data: ["User1", "User2"] });
handleApiResponse({ kind: "error", errorMessage: "Unauthorized 401" });

Best Practices & Gotchas

  • Use Discriminated Unions for Complex State: Add a common literal property (e.g. kind, type, status) to distinguish union members cleanly.
  • Use the in Operator for Object Narrowing: Check for property existence (if ("errorMessage" in response)) when narrowing objects without discriminant tags.
  • Avoid Overusing Untagged Unions: Unions of many complex object shapes without discriminant properties can become difficult to narrow cleanly.

Self-Check Challenge

Create a union type StringOrArray that accepts string | string[]. Write a function that prints the string's length if it's a string, or the array count if it's an array.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Recommended Courses & Books

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum