TypeScript - Assertion Functions & asserts

Assertion functions

function assertHasId(x: any): asserts x is { id: string } {
  if (!x || typeof x !== 'object' || !('id' in x) || typeof x.id !== 'string') {
    throw new Error('Invalid: no id');
  }
}

const maybe: unknown = JSON.parse('{"id":"u1"}');
assertHasId(maybe);
// here, maybe is { id: string }

Non-null assertions (use sparingly)

declare const el: HTMLElement | null;
el!.style.display = 'none'; // ok, but avoid; prefer checks