TypeScript for Real Projects · 22 min · 130 XP

Missing values without assertions

Make absence explicit and handle missing lookups without hiding valid zero or empty values.

With strictNullChecks, a value that might be absent must be handled before use. An optional property is read as its declared type plus undefined. Array.find can return undefined even when every array element is valid. Treat these as ordinary branches of your program, not compiler annoyances.

Check the lookup before reading fields
type Member = { id: string; credits?: number };
function availableCredits(members: readonly Member[], id: string): number | undefined {
  const member = members.find(item => item.id === id);
  if (member === undefined) return undefined;
  return member.credits ?? 0;
}

The result distinguishes a missing member from an existing member with zero credits. Optional chaining stops a property read when the receiver is null or undefined; it does not establish that data exists. The ?? operator defaults only null and undefined. In contrast, || also replaces zero, false and empty strings. Choose defaults from the product rule, not just to remove an error.

The non-null assertion value! disappears at runtime. It cannot make a failed lookup succeed. With noUncheckedIndexedAccess, arbitrary array and dictionary reads also include undefined. An early return usually communicates the missing case more clearly than an assertion.

Loading your workspace…