Dmytro Morar
TypeScript

Type management

Type management focuses on narrowing and validating types at runtime.

Type guards

function isString(value: unknown): value is string {
  return typeof value === "string";
}
function print(value: unknown) {
  if (isString(value)) {
    console.log(value.toUpperCase());
  }
}

Discriminated unions

type Shape = { kind: "circle"; r: number } | { kind: "square"; size: number };
function area(shape: Shape) {
  if (shape.kind === "circle") return Math.PI * shape.r ** 2;
  return shape.size * shape.size;
}

On this page