Safety
Intermediate

Narrowing and Runtime Boundaries

Use narrowing, unknown, type guards, and discriminated unions to safely handle untrusted data.

38 min
3 sections
narrowing
unknown
type-guards
api
1
2
3

01. Unknown Beats Any at Boundaries

Section 1 of 3

Every API response, webhook body, localStorage item, message queue payload, and user upload is untrusted. Model it as unknown until you validate or narrow it. any disables the safety net exactly where you need it most.

typescript
async function fetchJson(url: string): Promise<unknown> {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error("Request failed with status " + response.status);
  }
  return response.json();
}

function isObject(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null;
}

Exercise

Protect a webhook endpoint

Practice

Write a type guard for a payment webhook with eventId, type, and createdAt fields before routing it to business logic.

Back to Course