TSTypeScript
BeginnerLesson 5 of 15

Union & Literal Types – TypeScript

Restricting values to several types or fixed values.

A union type A | B allows several types. Before you use type-specific methods you have to narrow the type (narrowing), e.g. with typeof:

function formatiere(wert: string | number | null): string {
  if (wert === null) return "–";
  if (typeof wert === "number") return wert.toFixed(2);   // here: number
  return wert.toUpperCase();                               // here: string
}
console.log(formatiere(3.14159), formatiere("hallo"), formatiere(null));

let id: string | number = 5;
id = "A-17";
// id = true;   // Error

Literal types allow only certain fixed values. Together with unions they usually replace enums – without any additional runtime code:

type Richtung = "up" | "down" | "left" | "right";
type Wuerfel = 1 | 2 | 3 | 4 | 5 | 6;

function gehe(r: Richtung, schritte: number): string {
  return schritte + " steps toward " + r;
}
console.log(gehe("left", 3));
// gehe("diagonal", 1);   // Error: Argument of type '"diagonal"' is not assignable...

const wurf: Wuerfel = 4;

With as const TypeScript freezes an object or array into literal types. You derive types from it instead of maintaining them twice:

const FARBEN = ["rot", "gruen", "blau"] as const;
type Farbe = (typeof FARBEN)[number];            // "rot" | "gruen" | "blau"

const STATUS = { OFFEN: "offen", FERTIG: "fertig" } as const;
type Status = (typeof STATUS)[keyof typeof STATUS];   // "offen" | "fertig"

function setze(f: Farbe, s: Status) {
  console.log(f, s);
}
setze("rot", STATUS.FERTIG);
TipIf TypeScript makes a literal type too wide (e.g. let r = "up" becomes string), const, an annotation or as const helps.