BeCuriouzBeCuriouz

Learn something new every day

🔷 TypeScript
🔀

Union Types: One Value, Several Possible Types

💡 A union type (A | B) lets a value be one of several types, but you can only use members' shared operations until you narrow it to a specific type.

Sometimes a value could reasonably be more than one type. An ID might arrive as a number from a database or a string from a URL. A union type describes exactly this: a value that is one of several types. You write it with the vertical bar | between the options.

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

printId(101);      // ok
printId("202");    // ok
printId({ id: 1 }); // Error: object not assignable to number | string

Here number | string means the parameter accepts a number or a string, but nothing else. The catch: inside the function, TypeScript only lets you do things that are valid for every member of the union. You can concatenate id into a string (both numbers and strings allow that), but calling id.toUpperCase() fails — numbers have no such method.

To use the type-specific behavior, you narrow the union by checking which type you actually have at runtime. A simple typeof check tells TypeScript which branch it's in:

ts
function printId(id: number | string) {
  if (typeof id === "string") {
    console.log(id.toUpperCase()); // id is string here
  } else {
    console.log(id.toFixed(2));    // id is number here
  }
}

Unions aren't limited to primitives — you'll soon combine them with literal types (like "left" | "right") to model precise sets of allowed values.

🔀 Union Types: One Value, Several Possible Types — BeCuriouz