Skip to content

Runtime Validation

The Course
•
20 min study

A record validator answers two questions: is this the right shape, and do its values meet the application's rules? A minutes field can be a number and still be negative or infinite. A topic can be a string and still be blank.

The previous lesson used JavaScript's in operator to check that a property is present. After narrowing a value to a non-null object, checking "topic" in value lets TypeScript track that property, initially as unknown. Then typeof establishes whether it is text. Repeat for every field promised by your domain type.

Order checks from broad to specific: reject non-objects and null; check property presence; check primitive types; then check domain restrictions. Return early when a requirement fails. This avoids reading a property before establishing that reading it is meaningful.

A validator can recognize an existing record, or a parser can construct a clean new one. Constructing a new record lets you deliberately normalize text and keep only relevant fields. Avoid a broad assertion that accepts unknown input without examining it.

This lesson's guard promises only the fields and rules shown. Additional unrelated properties are allowed. If your application needs own-property-only checks or exact allowed keys, state and implement those rules separately. For imported JSON, prototype-related cases are less common, but tests should still establish the domain behavior you claim.

Read the checks from left to right

&& evaluates its right side only if the left side is true. || evaluates its right side only if the left side is false. This short-circuit behavior, introduced in JavaScript’s conditions lesson, makes the order important: first prove an object exists, then prove a property exists, then prove its type, then call its methods.

The following longer form has the same purpose as the compact guard below. Each successful check supplies evidence for the next statement. Number.isInteger, from JavaScript input validation, additionally rejects fractions; Number.isFinite rules out NaN and infinity.

Trace one property guardTypeScript
function hasTopic(value: unknown): boolean {
  if (typeof value !== "object" || value === null) {
    return false;
  }

  if (!("topic" in value)) {
    return false;
  }

  if (typeof value.topic !== "string") {
    return false;
  }

  return value.topic.trim() !== "";
}

console.log(hasTopic(null));
console.log(hasTopic({ topic: 25 }));
console.log(hasTopic({ topic: " Types " }));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
false
false
true

Predict, check, then run

Before running, write down the output and explain which information the checker knows. Click Check types first, then Check & run.

Predict, then runTypeScript
type Session = {
  topic: string;

  minutes: number;
};

function isSession(value: unknown): value is Session {
  if (typeof value !== "object" || value === null) {
    return false;
  }

  return (
    "topic" in value &&
    typeof value.topic === "string" &&
    value.topic.trim() !== "" &&
    "minutes" in value &&
    typeof value.minutes === "number" &&
    Number.isFinite(value.minutes) &&
    value.minutes >= 0
  );
}

console.log(isSession({ topic: "Types", minutes: 0 }));
console.log(isSession({ topic: " ", minutes: 25 }));
console.log(isSession(null));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
true
false
false

Read a real compiler error

This local example demonstrates the contract mismatch that untrusted input could hide.

Find and fix the type errorTypeScript
type Session = {
  topic: string;

  minutes: number;
};

const session = { topic: "Types", minutes: "25" };
const trusted: Session = session;

console.log(trusted.minutes);

Enable JavaScript to edit and type-check this example.

Check your diagnosis

Validate the incoming minutes rather than asserting the object is Session. This course rejects text minutes at a JSON-record boundary; a separate form parser may intentionally convert strings before creating a record.

From a yes/no guard to a parser

isSession answers yes or no about the value it was given. Because its predicate also rejects a blank topic, it is the kind of guard the previous lesson warned about: safe while its input is unknown, misleading if reused on a narrower union. It also cannot trim the topic, because a predicate returns a boolean, not a value.

A parser removes both limits. It checks the same facts, then constructs and returns a new record (or undefined when a check fails). The returned record contains only the modeled fields, normalized the way you chose, and the original input is untouched.

Your turn

Exercise

Runtime Validation: practice

Define Book with title:string and pages:number. Write a parser, parseBook(value: unknown): Book | undefined. Accept only a nonblank string title and whole-number pages of at least 1; return a new record with the title trimmed and no other fields. Print Notes: 120 pages for { title: " Notes ", pages: 120, shelf: "B2" }, Invalid for fractional pages, Invalid for null, and then title,pages for the keys of a parsed record that had a shelf field.

Your workspaceTypeScript
// Check the object and both fields, then construct the clean Book.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

A predicate can only say yes or no about the original value. To trim the title and drop shelf you must build and return a new object; return undefined wherever a check fails.

Hint 2: a first step

Return undefined early for non-objects and null, then check title with in and typeof in one if, and pages in another. Typeof number alone is not enough: the brief also requires a whole number of at least 1.

Show one solution
One possible solutionTypeScript
type Book = {
  title: string;

  pages: number;
};

function parseBook(value: unknown): Book | undefined {
  if (typeof value !== "object" || value === null) {
    return undefined;
  }
  if (
    !("title" in value) ||
    typeof value.title !== "string" ||
    value.title.trim() === ""
  ) {
    return undefined;
  }
  if (
    !("pages" in value) ||
    typeof value.pages !== "number" ||
    !Number.isInteger(value.pages) ||
    value.pages < 1
  ) {
    return undefined;
  }
  return { title: value.title.trim(), pages: value.pages };
}

function show(book: Book | undefined): string {
  return book === undefined ? "Invalid" : `${book.title}: ${book.pages} pages`;
}

console.log(show(parseBook({ title: " Notes ", pages: 120, shelf: "B2" })));
console.log(show(parseBook({ title: "Notes", pages: 2.5 })));
console.log(show(parseBook(null)));

const parsed = parseBook({ title: "Notes", pages: 1, shelf: "B2" });
console.log(Object.keys(parsed ?? {}).join(","));

Enable JavaScript to edit and type-check this example.

Text
Notes: 120 pages
Invalid
Invalid
title,pages

Each early return leaves the checker with more evidence: after the second if, value.title is a string, and after the third, value.pages is a number, so the final object literal type-checks as a Book without any assertion. Number.isInteger also rejects NaN and Infinity, so no separate finiteness check is needed. The return type Book | undefined makes callers like show handle failure, and only the parser decides what counts as valid, so no predicate can make a false claim about a narrower union.

Change it and explain it

Test missing title, missing pages, a blank title, text pages, Infinity and -1. Then remove one guard condition temporarily and find a test case that exposes the defect. Explain why a predicate annotation did not prove the validator itself correct.

Was this article helpful?

Your response is saved on this device.