iLearnNation field notes · 4 min
Why your TypeScript type does not validate a request
Turn an unknown JSON body into a small validated domain value, with explicit errors and useful tests.
Published 2026-10-16 · Original editorial draft
A type describes a promise
A request body can arrive from a browser, a script, or a broken client. Calling a value a Note in TypeScript does not make an incoming object satisfy the Note contract. Type assertions help the checker reason about your program; they do not inspect a network body for you.
For a notebook API, begin with an unknown value. Accept an object with a title string, trim it, enforce a small length limit, and reject unsupported fields. Only then create the domain value your application expects. This gives your service one clear boundary between untrusted input and validated data.
Test the cases you hope never arrive
Try a valid title first. Then send null, an array, a number, an empty title, a very long title, and an object with a role field. The last case matters: accepting extra fields and spreading a request into a database update can let an unrelated input change an unrelated property.
A useful error tells a learner what to fix: “Use a title between 1 and 120 characters.” The server still chooses the record owner from the authenticated session. A userId supplied by the browser is not permission to write another learner's notes.
Validation has several layers
Input shape validation answers whether a request has an acceptable form. Authorization answers whether this person may perform the operation. A database constraint protects an invariant even if another code path makes a mistake. None of these replaces the others.
Keep the layers small enough to test independently. A title validator should not send mail or query an unrelated account. A repository write should use parameterized SQL, rather than joining a title into a query string. A route should bound the body before parsing it.
An exercise worth keeping
Write down five invalid inputs before implementing the validator. Run them as tests. Change one validation rule, such as the maximum length, and check that the boundary cases still describe the behavior you intend.
Then remove a type assertion from a request handler and replace it with an explicit check. That small change makes the trust decision visible to the next reader.
Sources and practice
Original explanation; the TypeScript handbook and MDN's client-side form validation guide, reviewed 16 October 2026. Practice the same boundary in the data-and-forms activity.