Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 25 min · revision 3

Narrowing and Validating Data You Do Not Control

Turn a checked-at-runtime payload into types the compiler trusts: narrow unions with typeof, in and equality, and validate untrusted JSON with a type predicate.

Contentsand lesson path

What you will learn

  • Narrow union and unknown values with typeof, in, equality checks, type predicates and discriminated unions, and validate untrusted runtime data such as API responses before relying on its type.

Prerequisites: JavaScript Foundations

01. The task

The search feature you built in the async JavaScript lab now needs its module in TypeScript. Its data crosses a trust boundary: a fetch response parsed with JSON.parse arrives from a server, and the compiler has no way to see what the server sends. In JavaScript the module simply trusted the payload — and got away with it until the API changed.

To run the examples, make an empty folder and run npm install --save-dev [email protected] [email protected] in it once, the same versions as the lab. Every file in this lesson goes in that folder and runs with npx.

The TypeScript way to "get away with it" is a cast. Watch how little a cast buys:

TypeScript · cast-crash.ts
type SearchResponse = { results: string[]; total: number };

const payload =
  '{"total": 2, "hits": ["union types", "literal types"]}';

// The cast tells the compiler to trust the payload. It checks nothing.
const data = JSON.parse(payload) as SearchResponse;
console.log(data.total);
for (const hit of data.results) console.log(hit);
Expected output (npx tsc --noEmit --strict --pretty false cast-crash.ts)
exit code: 0 — the type-check passes
Expected output (npx tsx cast-crash.ts; path and stack frames trimmed)
2
…/cast-crash.ts:9
for (const hit of data.results) console.log(hit);
                       ^

TypeError: data.results is not iterable

The server sends its results under the key hits, but the type claims results. The compiler believed the cast, printed a plausible total, and the program then crashed on real users. The cast is a promise with no evidence behind it — the exact problem the previous lesson flagged: types are erased, so nothing checks a payload by itself. The task is to replace the promise with proof: a runtime check that both validates the data and produces a correctly typed value.

02. Step 1: say unknown instead of a guess

The honest type for data you have not examined is unknown. It is the safe counterpart to any: like any, any value fits into unknown, but unlike any, you cannot use an unknown value until you have narrowed it to something specific. Change the parser to tell the truth and the compiler starts working for you:

TypeScript · unknown.ts
function parsePayload(text: string): unknown {
  return JSON.parse(text);
}

const data = parsePayload('{"results": [], "total": 0}');
console.log(data.results);
Expected output (npx tsc --noEmit --strict --pretty false unknown.ts)
unknown.ts(6,13): error TS18046: 'data' is of type 'unknown'.

One error, at the first place the unproven value is used. This is unknown doing its job: not forbidding anything, but refusing to pretend. The value still is whatever the server sent — nothing changed at runtime — but the compiler now treats it as an unexamined claim, and every path from unknown to a usable value has to go through a check the compiler understands. Those checks are called narrowing.

03. Step 2: narrow with checks the compiler can follow

Narrowing means: the compiler tracks which checks have passed and refines the type inside each branch. The everyday tools, all plain JavaScript tests:

  • typeof value === 'string' narrows a union or an unknown to string (the other primitives likewise).
  • Array.isArray(value) narrows to an array — though not to an array of anything in particular, so element checks are still needed.
  • 'error' in payload narrows to the union members that have that property.
  • Comparing a discriminant field to its literal (payload.ok === false) narrows a union of object shapes to one member.

The last two combine into the workhorse pattern for UI data. A request has states, each state has different fields, and the compiler should not let you read data in the state where only message exists:

TypeScript · request-state.ts
type FetchState<T> =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: T }
  | { status: 'error'; message: string };

function render(state: FetchState<string[]>): string {
  switch (state.status) {
    case 'idle':
      return 'Type to search…';
    case 'loading':
      return 'Searching…';
    case 'success':
      return `${state.data.length} results`;
    case 'error':
      return `Failed: ${state.message}`;
  }
}

const states: FetchState<string[]>[] = [
  { status: 'idle' },
  { status: 'success', data: ['unions', 'literals'] },
  { status: 'error', message: 'network offline' },
];
for (const state of states) console.log(render(state));
Expected output
Type to search…
2 results
Failed: network offline

Each case narrows state to the member whose status matches, so state.data compiles only in the branch where the check guarantees it exists. Add a fourth state and the compiler flags this switch, but only because render promises a string and the new case would fall off the end without returning one. A switch in a function that returns nothing would compile silently with the case missing. To get the same protection in any switch, add a default branch that assigns the value to never: default: { const unhandled: never = state; return unhandled; }. A new, unhandled state then fails to compile with "Type ... is not assignable to type 'never'". This shape — a union of object types sharing one literal-typed field — is a discriminated union, and it is one of the most useful modelling patterns in typed frontend code.

Notice what made this free: the checks are ordinary JavaScript. typeof, in, Array.isArray and comparisons already run in your code; narrowing simply makes the compiler understand what each check proves, instead of you restating the proof in a cast. That is also why narrowing reads so well in review — a colleague sees a normal guard, and the types follow it.

04. Step 3: validate the payload with a type predicate

Now the payload itself. A chain of the checks from step 2, wrapped in a function whose return type is a type predicate — value is string[] in isStringArray below. A predicate is a boolean function with a promise attached: if it returns true, the compiler treats value as that type from then on. The compiler trusts the predicate's body without checking it, so a predicate that tests less than it claims (for example, only Array.isArray(value)) is a cast in disguise. That is what turns validation into a typed value instead of a promise backed by a cast. The parser returns a discriminated union of its own, so the caller must handle failure explicitly:

TypeScript · validate.ts
type SearchResponse = { results: string[]; total: number };
type Parsed<T> = { ok: true; value: T } | { ok: false; error: string };

function isStringArray(value: unknown): value is string[] {
  return Array.isArray(value) && value.every((item) => typeof item === 'string');
}

function parseSearchResponse(payload: unknown): Parsed<SearchResponse> {
  if (typeof payload !== 'object' || payload === null) {
    return { ok: false, error: 'Expected a JSON object' };
  }
  if (!('results' in payload) || !('total' in payload)) {
    return { ok: false, error: 'Missing results or total' };
  }
  if (!isStringArray(payload.results) || typeof payload.total !== 'number') {
    return { ok: false, error: 'results must be string[] and total a number' };
  }
  return { ok: true, value: { results: payload.results, total: payload.total } };
}

function show(text: string): void {
  const parsed = parseSearchResponse(JSON.parse(text));
  if (!parsed.ok) {
    console.log(`Rejected: ${parsed.error}`);
    return;
  }
  console.log(`${parsed.value.total} total; first: ${parsed.value.results[0]}`);
}

show('{"total": 2, "results": ["union types", "literal types"]}');
show('{"total": 2, "hits": ["union types", "literal types"]}');
show('{"total": 1, "results": [42]}');
show('"just a string"');
Expected output
2 total; first: union types
Rejected: Missing results or total
Rejected: results must be string[] and total a number
Rejected: Expected a JSON object

Compare this with the crash at the start. The same four payloads, but the malformed ones are now data: rejected with a reason the UI can show, instead of a TypeError in the console. Inside show, the check if (!parsed.ok) narrows both ways — in the early return parsed.error exists, after it parsed.value does. Notice there is no cast needed: TypeScript narrows payload directly after the in checks, so payload.results and payload.total are typed as unknown and still have to be validated before use.

Here is the same validator written with Zod 4. Install it in the same folder, then type-check and run the same four payloads:

TypeScript · schema.ts
import * as z from 'zod';

// One declaration: the runtime check, and the static type derived from it.
const SearchResponseSchema = z.object({
  results: z.array(z.string()),
  total: z.number(),
});
type SearchResponse = z.infer<typeof SearchResponseSchema>;

function show(text: string): void {
  const parsed = SearchResponseSchema.safeParse(JSON.parse(text));
  if (!parsed.success) {
    console.log(`Rejected: ${z.prettifyError(parsed.error)}`);
    return;
  }
  const data: SearchResponse = parsed.data;
  console.log(`${data.total} total; first: ${data.results[0]}`);
}

show('{"total": 2, "results": ["union types", "literal types"]}');
show('{"total": 2, "hits": ["union types", "literal types"]}');
show('{"total": 1, "results": [42]}');
show('"just a string"');
Terminal
npm install [email protected]
npx tsc --noEmit --strict --target es2022 --module nodenext schema.ts
npx tsx schema.ts
Expected output (npx tsx schema.ts; tsc prints nothing)
2 total; first: union types
Rejected: ✖ Invalid input: expected array, received undefined
  → at results
Rejected: ✖ Invalid input: expected string, received number
  → at results[0]
Rejected: ✖ Invalid input: expected object, received string

z.object and z.array describe the shape. safeParse returns a discriminated union, just like Parsed: { success: true, data } or { success: false, error }, so the same if narrows it. z.infer derives the SearchResponse type from the schema, so there is no second declaration to keep in step. The same payloads pass and fail as before; only the messages differ, and they now say where the data went wrong, such as results[0]. z.prettifyError formats the problems for people, and parsed.error.issues holds them as data. The --target and --module flags keep the command portable: Zod's declaration files use built-ins such as Map and Set, which the ES5 default target of TypeScript 5.x did not include. TypeScript 7 defaults to a modern target (ES2025), so on the pinned version the check also passes without the flags.

05. Check your understanding

Practice check · 3 questions

Narrowing under pressure

Three decisions from the validator you just wrote.

Q1. `payload: { kind: 'hit'; items: string[] } | { kind: 'miss'; reason: string }`. Inside `if ('reason' in payload) { ... }`, what does the compiler know?
Q2. In `isStringArray`, `Array.isArray(value)` alone is not enough. What does the extra `value.every((item) => typeof item === 'string')` rule out?
Q3. Why does the parser return `{ ok: true; value } | { ok: false; error }` instead of throwing on bad data?
Practice only: not graded, not saved, not evidence.

06. Apply it

Find one place in your own code that consumes await response.json() — the search UI from the fetch lesson if you have it. Replace any cast with an unknown-typed parse, write a predicate for the shape you actually use, and return a Parsed-style result so the UI renders the rejection reason instead of crashing. Test it the way this lesson did: one valid payload, one with a renamed key, one with a wrong-typed element, one that is not even an object. The skill practice for TypeScript Foundations asks for exactly this on the search module — validators first, then zero type errors with any banned.

07. Review prompt

Without looking back: list the four narrowing tools from step 2 and what each one proves. What does a type predicate (value is string[]) add over returning a plain boolean? And explain why unknown plus validation is safer than any, when both accept every value.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check