Skip to content
FrontDepth, Home

TypeScript

Validating data at the boundary

Why types are only a promise for data from fetch, JSON.parse, storage, the URL, forms and postMessage; why as, ! and satisfies check nothing at run time; and how to parse data once at the edge with a schema (Zod 4), handle invalid data and trust the types after that.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

This topic starts at Junior level.

JuniorConcept

Where types are only a promise

TypeScript checks the code you write. When the program runs, the types are gone (), and nothing checks that a value really has the type the code says. Inside your own code that is fine: the compiler has checked every assignment. At the boundary, where data comes from outside the program, the compiler has nothing to check, and the type is a promise someone else has to keep.

Where data enters a frontend app, and what the DOM types give you:

  • await response.json(): any
  • JSON.parse(text): any
  • localStorage.getItem(key): string | null, usually followed by JSON.parse
  • new URLSearchParams(location.search).get("page"): string | null
  • new FormData(form).get("qty"): FormDataEntryValue | null, a string or a File
  • event.data in a message event (postMessage, workers): any
  • globals set by third-party scripts: whatever you declared them to be

any is the dangerous one. It is assignable to every type, so it flows into typed code without a single error:

TypeScript
type Order = { id: string; total: number; status: "paid" | "shipped" };

async function loadOrder(id: string): Promise<Order> {
  const response = await fetch(`/api/orders/${id}`);
  return response.json(); // any, accepted as Order
}

const order = await loadOrder("42");
console.log(order.total.toFixed(2));

This compiles. If the API sends "total": "19.90" as a string, renames the field, or answers a 404 with { "error": "Not found" }, the TypeError appears in toFixed, far from loadOrder, or a wrong value reaches the screen without any error. Note the 404 case: MDN points out that a fetch() promise does not reject on HTTP error statuses, so the code has to check response.ok itself.

Strings from the URL, storage and forms have a smaller problem. Their type is honest (string | null), but the string still has to become a number, a date or one of your union members, and that conversion can fail.

The fix is not a better type but a check: , code that looks at the value while the program runs and either produces a typed value or reports what is wrong. The rest of this topic is about writing that check once, at the edge, and trusting the types after it.

JuniorConcept

as is a claim, not a check

A tells the compiler "treat this value as this type". The TypeScript handbook is explicit: assertions are removed at compile time, there is no runtime check, and no exception is thrown if the assertion is wrong.

TypeScript
type ViewSettings = { pageSize: number; view: "grid" | "list" };

const settings = JSON.parse(localStorage.getItem("view-settings") ?? "{}") as ViewSettings;
// Compiles. If storage holds {"pageSize":"20"}, this is the string "205"
const next = settings.pageSize + 5;

Assertions have honest uses, where you know more than the compiler can: document.getElementById("chart") as HTMLCanvasElement for an element your own HTML defines, for example. They are wrong wherever the value comes from outside.

TypeScript does reject some assertions: it only allows converting to a more specific or a less specific version of a type. "42" as number is an error ("neither type sufficiently overlaps"). The rule is easy to get around, and the workaround is a clear warning sign in a review:

TypeScript
// Error: conversion of type 'string' to type 'number' may be a mistake
const a = "42" as number;
// Compiles: first to unknown, then to anything. b is still the string "42"
const b = "42" as unknown as number;

as unknown as T (or as any as T) means "I know the compiler disagrees". It is occasionally right in a test helper; in application code it almost always hides a missing conversion or a missing check. And at the boundary the overlap rule protects nothing anyway: any overlaps with every type, so JSON.parse(text) as User always compiles.

Assertions in disguise

Some code asserts without writing as:

TypeScript
async function getJson<T>(url: string): Promise<T> {
  const response = await fetch(url);
  return response.json();
}

const user = await getJson<User>("/api/me"); // nothing is checked

T appears only in the return type, so the caller picks it and nothing connects it to the data: an as with nicer syntax. The same goes for a declare global block that types a third-party script's window property, and for a storage helper that hides JSON.parse(text) as T. Treat each of them as what it is, an unchecked claim, and keep it next to code that checks.

JuniorConcept

Annotation, satisfies and as

There are three ways to attach a type to a value you write in code, from strictest to loosest:

TypeScript
type Route = { path: string; auth: boolean };

// Annotation: the value must match, and the variable gets exactly this type
const routes: Record<string, Route> = {
  home: { path: "/", auth: false },
  account: { path: "/account", auth: true },
};
const typo = routes.acount; // no error: any string key is allowed

// satisfies: the value must match, and the variable keeps its own, narrower type
const routes2 = {
  home: { path: "/", auth: false },
  account: { path: "/account", auth: true },
} satisfies Record<string, Route>;
// Error: property 'acount' does not exist
const typo2 = routes2.acount;

// as: only checks that the types overlap
const home = { path: "/" } as Route; // compiles; home.auth is undefined at run time
  • An annotation checks the value against the type and then forgets the value: the variable has exactly the annotated type, so the keys above become "any string".
  • satisfies (TypeScript 4.9) checks the value against the type and keeps the inferred type: the keys stay home and account, literal values such as "dark" stay literal, and missing or extra properties are still errors.
  • as accepts a value with fewer properties than the type, as long as one type is assignable to the other. That is how home ends up without auth.

None of them checks anything at run time. satisfies is about values written in the source; it cannot help with JSON.parse, because that value does not exist until the program runs. Data from outside needs run-time code.

A rule of thumb: annotate function parameters and return types; use satisfies for literal objects whose exact shape you want to keep, such as configuration, lookup tables and route maps; keep as for the rare case where you really know more than the compiler, with a comment that says why.

MiddleConcept

Parse, don't validate

Alexis King's 2019 article "Parse, don't validate" gave the idea its name. A validator checks data and answers yes or no, and the rest of the code keeps working with the unchecked type. A parser, in her words, "consumes less-structured input and produces more-structured output", or fails. In TypeScript terms: take unknown or a string, return a typed value.

TypeScript
// Validates: the caller still holds a string and converts it again somewhere
function isValidPage(value: string | null): boolean {
  return value !== null && /^[1-9]\d*$/.test(value);
}

// Parses: the caller gets a number that is known to be valid
function parsePage(value: string | null): number {
  if (value === null) return 1;
  if (!/^[1-9]\d*$/.test(value)) throw new RangeError(`Invalid page: ${value}`);
  return Number(value);
}

After isValidPage returns true, the code still holds a string, and each place that uses it converts it again, maybe differently. After parsePage there is only a number. The proof that the check happened travels in the type.

For objects, start from unknown, never from any. With unknown, TypeScript forces every access through a check ():

TypeScript
type Line = { sku: string; qty: number };

function parseLine(input: unknown): Line {
  if (typeof input !== "object" || input === null) {
    throw new TypeError("line: expected an object");
  }
  if (!("sku" in input) || typeof input.sku !== "string") {
    throw new TypeError("line.sku: expected a string");
  }
  if (!("qty" in input) || typeof input.qty !== "number" || !Number.isInteger(input.qty) || input.qty < 1) {
    throw new TypeError("line.qty: expected an integer >= 1");
  }
  return { sku: input.sku, qty: input.qty };
}

The function returns a new object with only the known fields, so extra data from the server does not leak further.

This works, but it grows quickly: nested objects, arrays, optional fields, every error instead of the first, and a type and a set of checks that you keep in sync by hand. A (input is Line) has the same weakness: if its body checks less than its type promises, it lies exactly like as, and the compiler trusts it. That is why most projects use a schema library, which derives both the check and the type from one definition.

MiddleFramework

Schemas with Zod 4

A schema library describes the expected shape once, as a value. At run time it parses data against that value; at compile time it gives you the type. Zod is a common choice, and the examples use Zod 4 (import * as z from "zod").

TypeScript
import * as z from "zod";

const Order = z.object({
  id: z.string(),
  total: z.number().nonnegative(),
  status: z.enum(["paid", "shipped", "cancelled"]),
  customerEmail: z.email(),
  note: z.string().optional(),
});

type Order = z.infer<typeof Order>;
// { id: string; total: number; status: "paid" | "shipped" | "cancelled";
//   customerEmail: string; note?: string | undefined }
  • Order.parse(data) returns a typed value or throws a ZodError. The value is a new object (zod.dev: a deep clone), and keys the schema does not list are stripped by default.
  • Order.safeParse(data) does not throw. It returns { success: true, data } or { success: false, error }, a discriminated union, and error.issues lists every problem with its path and message.
  • In Zod 4 string formats are top-level functions (z.email(), z.url(), z.uuid()); the older z.string().email() still works but is deprecated.
TypeScript
async function loadOrder(id: string): Promise<Order> {
  const response = await fetch(`/api/orders/${id}`);
  if (!response.ok) throw new Error(`GET /api/orders/${id}: HTTP ${response.status}`);
  return Order.parse(await response.json());
}

Strings from the URL or a form need converting first. z.coerce.number() runs Number(input) before checking:

TypeScript
const ListParams = z.object({
  page: z.coerce.number().int().min(1).default(1),
  sort: z.enum(["newest", "price"]).catch("newest"),
});

const params = ListParams.parse(Object.fromEntries(new URLSearchParams(location.search)));
// ?page=3&sort=name gives { page: 3, sort: "newest" }

.default(1) applies when the key is missing. .catch("newest") replaces an invalid value instead of failing, which suits URL parameters people edit by hand. Mind what Number() does: an empty ?page= becomes 0 (rejected here by .min(1)).

Transforms change the output type: z.iso.datetime().transform((s) => new Date(s)) accepts an ISO string and gives a Date. z.input<typeof S> and z.output<typeof S> name the two sides; z.infer is the output.

MiddleConcept

Handling invalid data

Parsing helps only if failure is handled on purpose, and the right reaction depends on where the data came from.

API responses: fail loudly, close to the source. A response that does not match the schema is a bug or a contract change between client and server. Throw at the boundary with a message that names the endpoint and the issues, let the error boundary or the data library show an error state, and report it. Rendering half a page from data you know is wrong is worse.

TypeScript
async function getJson<T>(url: string, schema: z.ZodType<T>): Promise<T> {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`${url}: HTTP ${response.status}`);
  const result = schema.safeParse(await response.json());
  if (!result.success) {
    throw new Error(`${url}: unexpected response\n${z.prettifyError(result.error)}`);
  }
  return result.data;
}

Here T is tied to the schema, so the return type is earned, not claimed. z.prettifyError turns the issues into lines like "✖ Invalid input: expected number, received string → at total".

Stored data: fall back. What sits in localStorage may have been written by an older version of the app or edited by hand. Parse it, and if that fails, use defaults: the user loses a preference, not the page.

TypeScript
const ViewSettings = z.object({ pageSize: z.int().min(10).max(100), view: z.enum(["grid", "list"]) });
const DEFAULT_VIEW = { pageSize: 20, view: "grid" } satisfies z.infer<typeof ViewSettings>;

function readViewSettings(): z.infer<typeof ViewSettings> {
  try {
    const result = ViewSettings.safeParse(JSON.parse(localStorage.getItem("view-settings") ?? "null"));
    return result.success ? result.data : DEFAULT_VIEW;
  } catch {
    return DEFAULT_VIEW; // JSON.parse throws on malformed text
  }
}

User input: show the issues. For a form, map the issues to fields: z.flattenError(error).fieldErrors gives { email: ["Enter a valid email"] }, and custom messages go in the error parameter, as in z.email({ error: "Enter a valid email" }). Validate on the server as well: the client-side check is for the user's convenience, and the server cannot trust it.

Messages from other windows: check the sender first. MDN's advice for postMessage is to verify event.origin and then still verify the syntax of the message. Drop what does not match.

Avoid the quiet middle ground: .catch() or ?? 0 on every field of an API response turns a broken contract into wrong numbers on the screen, with nothing in the logs.

MiddlePitfalls

Other unchecked claims: !, definite assignment, guards

as is not the only way to tell the compiler something it cannot verify. All of these vanish at run time too.

The non-null assertion !. value! removes null and undefined from the type; the handbook calls it effectively a type assertion. At the boundary it turns a missing value into a silent bug:

TypeScript
const orderId = new URLSearchParams(location.search).get("order")!;
// Without ?order= in the URL this requests /api/orders/null
fetch(`/api/orders/${orderId}`);

null inside a template literal becomes the text "null", so instead of a clear error the app asks the server for an order that does not exist. Check and handle it: if (!orderId) return showNotFound();.

Definite assignment !:. let config!: Config or a class field client!: ApiClient tells TypeScript the value will be set before anyone reads it, so it skips the "used before being assigned" check:

TypeScript
let config!: { apiUrl: string };

export function initConfig(apiUrl: string) {
  config = { apiUrl };
}

export function ordersUrl() {
  return `${config.apiUrl}/orders`; // TypeError if initConfig has not run yet
}

If the order of calls changes, config is undefined. Initialise at the declaration, pass the value as a parameter, or type it Config | undefined and check.

Type guards that check less than they promise.

TypeScript
function isOrder(x: unknown): x is Order {
  return typeof x === "object" && x !== null && "id" in x;
}

After isOrder(data) the compiler treats data as a complete Order, although only id was checked. The predicate is an assertion with a function around it.

Declarations for globals. A declare global entry for a property that a third-party script sets on window is a promise about code you do not control; the script may be blocked or not loaded yet. Type it as optional and check before calling it.

Indexing. Without noUncheckedIndexedAccess, items[0] and byId[key] are typed as present even when they are not. With the flag on, their type includes undefined.

In review, these are the places to stop: !., !:, x is T, declare global and as. Each one needs a reason that holds at run time, not just at compile time.

SeniorConcept

Validate once, at the edge

Validation belongs where data enters the program, and only there. Inside, the types are true because the compiler checked every step; checking again in each component costs code and time, and tells the next reader that nobody trusts the types.

Picture the app as a typed core inside a thin edge:

Text
fetch, storage, URL, form, postMessage
        |  unknown, any or string
        v
  edge: parse with a schema  --fail-->  error state, report, fallback
        |  Order, ViewSettings, ListParams
        v
  typed core: components, hooks, state (no casts, no re-checks)

What that means in practice:

  • One API module owns fetch. Every endpoint function returns parsed data, as in getJson(url, Order), and components never call response.json() themselves. With a data library such as TanStack Query, parse inside the query function, so the cache only ever holds valid data.
  • Storage and URL helpers own JSON.parse and get. readViewSettings() or a useListParams() hook returns typed values; nothing else touches the raw strings.
  • Types come from the schemas. type Order = z.infer<typeof Order> instead of a hand-written type next to the schema: two definitions of one shape drift apart.
  • Generated types are still a promise. Types generated from an API description, or shared with a TypeScript backend, describe what the server should send. The running server can still differ, because of a deploy order, a proxy error page or an old cached response, so responses are still parsed at the edge.
  • Each source gets its own reaction. API responses fail loudly, stored data falls back to defaults, user input shows messages, and messages from other origins are dropped unless the origin and the shape match.

What it costs

Parsing walks the whole value, so its cost grows with the size of the data. For typical responses it is small next to the network, but parse once per response, not on every render, and measure before optimising a large payload. Bundle size counts too: Zod Mini (zod/mini) is a tree-shakable variant of Zod with a functional API, for pages where every kilobyte matters.

The payoff is a codebase where as and ! are rare enough to stand out. When a value inside the core has a type, that type was either computed by the compiler or produced by a parser, and nothing in between asks you to believe it.

SeniorConcept

Schemas when the data changes

Data at the boundary changes. The server adds a field or renames one, and an older version of your app wrote storage in another shape. The schema decides what happens then.

Unknown keys. z.object strips keys it does not list, so a new field from the server is ignored and nothing breaks. z.strictObject rejects unknown keys: right for data you fully own, like a configuration file, but for API responses it turns every additive change on the server into a failure in the client. z.looseObject keeps unknown keys, and its type allows them.

Stored data with versions. Store a version number with the data, parse with a discriminated union, then migrate to the current shape:

TypeScript
const SettingsV1 = z.object({ version: z.literal(1), compact: z.boolean() });
const SettingsV2 = z.object({ version: z.literal(2), density: z.enum(["compact", "comfortable"]) });
const StoredSettings = z.discriminatedUnion("version", [SettingsV1, SettingsV2]);

function migrate(stored: z.infer<typeof StoredSettings>): z.infer<typeof SettingsV2> {
  if (stored.version === 2) return stored;
  return { version: 2, density: stored.compact ? "compact" : "comfortable" };
}

Anything that matches neither version falls back to defaults. Without the version field you can only guess which shape you are reading.

null, undefined and missing. JSON has null but no undefined. An API that sends "note": null fails z.string().optional(), which accepts only undefined or a missing key. Use .nullable() for null, or .nullish() for both, and decide whether the rest of the code should see null at all; a transform at the edge can turn it into undefined once.

Input and output types. With coercion, transforms and defaults, what arrives (z.input) and what your code holds (z.output) differ: a form's input has strings, its output numbers and dates. Functions that handle the raw side, such as test fixtures or a form's initial values, need the input type.

Mocks drift too. A hand-written mock of an API response keeps passing after the real API changes. If fixtures are parsed with the same schemas, or typed as z.input<typeof Order>, an outdated fixture fails as soon as the schema changes. The schema then also documents the contract in one place that both the code and the tests read.

Zod 4 changed details here compared with Zod 3, such as .default() short-circuiting on undefined and the input type of z.coerce schemas becoming unknown. When you upgrade, read the migration guide on zod.dev rather than relying on memory.

SeniorInterview tips

Interview tips

A 30-second answer. "TypeScript's types are erased, so they only describe data the compiler has seen. Anything from outside, such as fetch().json(), JSON.parse, storage, URL parameters, forms and postMessage, arrives as any, unknown or a string, and as only silences the compiler. I parse that data once at the edge with a schema, Zod for example, which checks the value at run time and gives me the type through z.infer. Invalid data is handled per source: API errors fail loudly, stored data falls back, form input shows messages. After the edge I trust the types and avoid casts."

Questions you are likely to get

  • What is the difference between as, an annotation and satisfies? An annotation checks and widens to the annotated type; satisfies checks and keeps the inferred type; as only requires the types to overlap. None of them runs at run time.
  • Why is as unknown as T a red flag? It bypasses the only check as has. Ask which conversion or validation is missing.
  • How do you type a fetch wrapper? Not getJson<T>(url): Promise<T>, which is a disguised cast, but a function that takes a schema and returns its output type.
  • parse or safeParse? parse throws, which suits places where failure is exceptional and an error boundary handles it; safeParse returns a result for places that react locally, such as forms and storage.
  • Where do you validate? Once, where data enters: the API module, storage and URL helpers, message listeners. Not in every component.
  • What does ! do at run time? Nothing. It removes null and undefined from the type only.

Mistakes that cost points

  • Saying TypeScript "validates" API responses, or that a generic type parameter makes fetch type-safe.
  • Proposing strictObject for third-party API responses without discussing what happens when the API adds a field.
  • Swallowing invalid data with defaults everywhere: wrong numbers on screen are harder to debug than an error.

Senior signal

Talk about the boundary as a design decision: which module owns each source, how schemas are shared with the server or generated from its description, how fixtures stay in sync, how failures are reported, and what validation costs in bundle size and CPU time for large payloads.

JuniorReview checklist

What to check when reviewing code that handles outside data

Use this list when you review code you did not write that reads data from outside the program: a teammate's pull request, a library's example or an AI assistant's suggestion. Unchecked data compiles exactly like checked data, so the problem shows up later, as a crash far from the cause or a wrong value on screen.

  • Does every value from fetch, JSON.parse, storage, the URL, a form or postMessage pass through a parser before typed code uses it? Search for .json(), JSON.parse, getItem(, .get( and event.data, and follow each value: if the next step is as, an annotation or a Promise<T> return, its type is unchecked.
  • Is every as, as unknown as, ! and !: justified by something true at run time? A comment should say why the claim holds; as unknown as T and ! on a URL parameter or a storage value usually mean a missing check.
  • Is the HTTP status checked before the body is parsed? fetch resolves on a 404 or 500; without response.ok the code parses an error page or an error object as if it were data.
  • Are types derived from the schemas (z.infer, z.input) instead of written next to them? Two definitions of one shape drift; look for a hand-written type Order beside an Order schema.
  • Are string conversions deliberate? Number("") and z.coerce.number() of an empty string give 0, a missing URL parameter is null, and FormData.get may return a File; check that each case has a rule such as .min(1), a default or an error.
  • Does each failure path do something visible? An API mismatch should throw or report with the endpoint named, stored data should fall back to defaults, and form errors should reach the fields; a silent .catch() or ?? 0 on response data hides a broken contract.
  • Do message listeners check event.origin before reading event.data? MDN's advice is to verify the sender and then the message's syntax; a listener without an origin check accepts data from any window.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    3 predict-output · 4 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    7 questions