Typescript Foundations / Advanced Types

Union Types

A Union Type means a value can be one of several types.

βœ… Syntax

let value: string | number;
value = "Hello";      // βœ… OK
value = 123;          // βœ… OK
value = true;         // ❌ Error

βœ… Example: Function with Union Type

function printId(id: number | string) {
   console.log("Your ID is: " + id);
}
printId(101);        // OK
printId("A102");     // OK

πŸ”Ž Type Narrowing with Union Types

When you use union types, TypeScript requires you to narrow the type before performing operations that are specific to one type.

function formatInput(input: string | number) {
if (typeof input === "string") {
   return input.toUpperCase();        // βœ… TypeScript knows it's a string
}
   return input.toFixed(2);           // βœ… input is number here
}

πŸ§ͺ Union in Object Properties

type Status = "loading" | "success" | "error";
function handleStatus(status: Status) {
   if (status === "loading") {
       console.log("Loading...");
   } else if (status === "success") {
       console.log("Success!");
   } else {
       console.log("Something went wrong.");
   }
}

βœ… This is also called a string literal union β€” often used for enums or state machines.


🧱 Union Types with Arrays

let data: (string | number)[] = ["Alice", 25, "Bob", 42];
data.forEach(item => {
   if (typeof item === "string") {
      console.log(item.toUpperCase());
   } else {
      console.log(item.toFixed(1));
   }
});

🧠 Use Cases

Use Case

Why Union Types Help

Form inputs

Value can be `string

API responses (success/error)

Response can be two different shapes

Optional fields

Value can be `type

Status indicators

`β€œloading”


🚫 Pitfall to Avoid

You cannot directly use methods unless you first narrow the type:

function getLength(input: string | number) {
   return input.length; //❌ Error: 'length' not available on number
}

// Use narrowing:
if (typeof input === "string") {
   return input.length;                 // βœ…
}