On this page
  1. asserts
  2. Syntax & Overview
  3. Notes & Pitfalls
  4. Example

asserts

Prev: `is` | Up: builtins | Next: `infer`
Rel: builtins, Structural Typing & Narrowing
Ref: TypeScript Docs — asserts
Tags: #public #web #typescript #builtins #tier/standard


Syntax & Overview

function assertDefined<T>(v: T): asserts v is NonNullable<T>

Narrows the argument's type for the remainder of the calling block if the function returns normally (without throwing).

Notes & Pitfalls

Example

function assertDefined<T>(val: T | null | undefined, msg = "Missing"): asserts val is T {
  if (val == null) throw new Error(msg);
}

function greet(name?: string): string {
  assertDefined(name);
  return name.toUpperCase(); // narrowed to `string`
}

Linked from

Related notes