By Chason ArthurRevision 104.027Published Updated

Comparison / Choose a boundary

Choose the mechanism for the failure.

TypeScript checks the program before it runs. A runtime validator checks the data that actually arrives. This lab uses both, then protects the workflow and asynchronous results separately.

This comparison separates the implementation pattern from the environment used to explore it. A general playground is useful for editing freely; this lab adds a fixed failure, a readable execution trace and a direct path from the result to its source.

Where each choice fits

ApproachUseful whenTradeoffConnection to this lab
TypeScript assertionAn invariant has already been established elsewhere.Adds no runtime data validation.The broken price example shows the consequence of trusting it too early.
Hand-written validatorA small, inspectable contract with a few fields.You maintain every edge case and error message.Used here to make the actual checks easy to follow.
Shared schema or generated API typesMany endpoints or consumers must agree on a contract.Generated static types still need a trustworthy runtime boundary.Extend this lab by generating types and validating the received payload.
Official TypeScript PlaygroundExplore compiler behavior, type relationships and emitted JavaScript.A focused type experiment asks a different question from a complete UI workflow.Use it beside this lab to isolate the branded-ID or conditional-type example.
StackBlitzEdit and run a larger frontend or Node project in an online development environment.A general IDE leaves the learning path and failure scenario to the author.This lab supplies predetermined failures, plain-language traces and a matching source package.

Compare the same input

  1. Choose one scenario and predict the outcome.
  2. Run it without safeguards and retain the visible result.
  3. Change only the implementation, then run again.
  4. Inspect the source responsible for the difference.
  5. Name the guarantee that changed and the guarantee that remains outside the experiment.

The React application runs real compiled TypeScript against three invented sample responses. It makes no customer API calls. The public controls choose reviewed examples; they do not execute visitor-supplied code.

Run the comparison

Primary references and further reading

References support the language and runtime concepts. The lesson, scenarios and explanations are original Zyel Lab material.

Keep exploring

Follow the question you have next.

Build the safeguards

Eight explained steps, tradeoffs, pitfalls and a checkpoint before moving on.

Read the tutorial

Compare the choices

Choose a pattern and an environment for the problem you actually have.

Compare approaches

Lab discussion / TypeScript Boundary Lab

What would you try next?

Ask about the code, compare an approach, or describe an edge case. Reader comments are reviewed before publication.

All lab discussions

Reader comments

Open the discussion to read and add reader comments.

Read or write a comment →

Code walkthrough

Follow the implementation in code.

These short excerpts connect the lab’s behavior to its implementation. Each example links to the full tutorial step for its context, tradeoffs and checkpoint. Names and dependencies belong to that source; the excerpts are not standalone programs.

Example 01 · Tutorial excerpt

Accept external data as unknown

Read parseQuote in the code viewer. It first checks object shape, then identifier formats, then safe whole-number cents. It returns a discriminated success-or-error result. It also constructs a new object, so unrelated incoming properties do not silently become domain state. Validation is a business boundary: zero is allowed here, a negative price is not.

export type Result<T> =
  | { ok: true; value: T }
  | { ok: false; error: string };

Read the full tutorial step

Example 02 · Tutorial excerpt

Keep identifiers from trading places

Both IDs are strings at runtime, but their meanings differ. Brand<string, Name> separates CustomerId and QuoteId in checked code. The brand is introduced only after the validator checks the prefix. The negative type tests deliberately try assigning one ID type to the other. They use @ts-expect-error so a later change that removes the distinction fails type checking.

type Brand<T, Name extends string> =
  T & { readonly __brand: Name };
type CustomerId = Brand<string, "CustomerId">;

Read the full tutorial step

Example 03 · Tutorial excerpt

Represent the states that can actually exist

Read State and transition. An approved state contains a verified quote and an approver. Idle does not carry those fields. The approve transition still checks the current state and a nonempty approver because callers can request an inappropriate action at runtime. A tagged union makes the data contract precise; the transition function enforces workflow rules.

type State =
  | { status: "idle" }
  | { status: "ready"; quote: Quote }
  | { status: "approved"; quote: Quote; approvedBy: string };

Read the full tutorial step

Example 04 · Tutorial excerpt

Choose which asynchronous result is allowed to win

Try competing responses. The older request deliberately takes longer. The broken path assigns whichever response finishes last. The guarded path gives each request a generation and accepts only the latest one. Completion order is not user intent. The trace tells you when a late result was ignored rather than pretending it never happened.

const mine = ++latest;
await waitForResponse();
if (guarded && mine !== latest) return;

Read the full tutorial step

Example 05 · Tutorial excerpt

Turn the example into a reusable boundary

Download the matching source and run type checking plus the five behavioral tests. Extend the validator with a currency field and define a rejected state with a reason. Write the expected failure first, implement the smallest change, then explain why the runtime check and the state change belong in different functions.

node --test tests/typescript.test.mjs
# From the development source package:
pnpm run typecheck

Read the full tutorial step