TypeScript for Real Projects · 28 min · 180 XP

Validate before you trust

Validate untrusted values and build a small trusted object before passing it into application code.

JSON, storage and network responses can violate your type declarations. Receive them as unknown. Check object-ness, null, arrays and each required field before constructing your domain value. A string containing digits is still a string; validation and coercion are different product decisions. This lesson rejects invalid values instead of silently converting them.

A predicate needs real evidence
function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function readTitle(value: unknown): string | undefined {
  if (!isRecord(value) || typeof value.title !== "string") return undefined;
  return value.title.trim() || undefined;
}

A user-defined predicate is a promise to the checker. TypeScript checks that its implementation returns a boolean, but it does not prove the predicate tells the truth. Test it with hostile and malformed inputs. A parser returning a success/error union can be clearer because it creates the validated output and explains a failure. For larger schemas a validation library can centralize these checks; the boundary still needs runtime evidence.

Loading your workspace…