TypeScript theorytheory 0/50 · 0%
Types · easy

6. Union and literal types

Values that can be one of several fixed shapes or values.

A union type (`A | B`) says a value can be either shape. Literal types narrow a primitive down to exact values, and combining literals into a union creates a lightweight enum-like type.

ts
type Chain = "ethereum" | "polygon" | "arbitrum";

function explorerUrl(chain: Chain): string {
  if (chain === "ethereum") return "https://etherscan.io";
  return `https://${chain}scan.io`;
}

TypeScript narrows the type inside `if`/`switch` branches based on comparisons, so inside `if (chain === "ethereum")` the compiler knows `chain` is exactly `"ethereum"`. This is called control-flow narrowing and is central to writing safe union-handling code.

Check your understanding

  1. 1. What does `"ethereum" | "polygon"` describe?

  2. 2. What is 'narrowing'?

  3. 3. Inside `if (chain === "ethereum")`, what type does `chain` have?