TSTypeScript

TypeScript: Advanced – code examples

Contents

satisfies for configurations

Advanced#satisfies#configuration#record
Use case: Check configuration objects or lookup tables without losing their exact types.
type Farbe = "rot" | "gruen" | "blau";
type RGB = [number, number, number];

const palette = {
  rot: [255, 0, 0],
  gruen: "#00ff00",
  blau: [0, 0, 255]
} satisfies Record<Farbe, string | RGB>;

console.log(palette.rot.at(0));
console.log(palette.gruen.toUpperCase());

With satisfies, rot stays a tuple and gruen stays a string (with an annotation both would only be string | RGB). If a color is missing or there is a typo, the compiler reports it.

Mapped type with key remapping

Advanced#mapped type#keyof#template literal
Use case: Build types derived automatically from a data model (getters, forms, events).
interface Person {
  name: string;
  alter: number;
}

type Getter<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type Schreibgeschuetzt<T> = { readonly [K in keyof T]: T[K] };

const g: Getter<Person> = { getName: () => "Ada", getAlter: () => 36 };
const fest: Schreibgeschuetzt<Person> = { name: "Ada", alter: 36 };
console.log(g.getName(), g.getAlter(), fest.name);

[K in keyof T] loops over all keys, as renames them: name becomes getName. Capitalize is a built-in string type.

Conditional type with infer

Advanced#conditional#infer#type function
Use case: Derive types from other types, e.g. the element type of an array or the result of a promise.
type ElementVon<T> = T extends (infer U)[] ? U : T;
type NichtNull<T> = T extends null | undefined ? never : T;
type Ausgepackt<T> = T extends Promise<infer V> ? V : T;

const a: ElementVon<string[]> = "text";
const b: NichtNull<string | null> = "not null";
const c: Ausgepackt<Promise<number>> = 42;
console.log(a, b, c);

T extends ... ? X : Y is a ternary at the type level; infer U pulls out the inner type. This is how ReturnType, Awaited and NonNullable are built.

Branded types

Advanced#brand#nominal#type safety
Use case: Prevent mix-ups: euros vs. dollars, UserId vs. OrderId.
type Euro = number & { readonly __marke: "Euro" };
type Dollar = number & { readonly __marke: "Dollar" };

const euro = (n: number) => n as Euro;
const dollar = (n: number) => n as Dollar;

function zahle(betrag: Euro): void {
  console.log("Paying " + betrag + " EUR");
}
zahle(euro(5));
// zahle(dollar(5));   // compiler error
// zahle(5);           // compiler error

The "brand" exists only in the type system and costs nothing at runtime. Only the constructor functions may use as.