Typed API contracts
Local baseline: Node.js 22.16.0. Actual TypeScript source execution, independent tsc check. TypeScript 5.8.3; no third-party packages.
Try the local example
type Result = {ok:true; value:{quantity:number}} | {ok:false; error:string};function parseOrder(input: unknown): Result { if (typeof input !== 'object' || input === null || Array.isArray(input) || !('quantity' in input)) return {ok:false,error:'shape'}; const q = input.quantity; if (typeof q !== 'number' || !Number.isSafeInteger(q) || q < 1 || q > 100) return {ok:false,error:'quantity'}; return {ok:true,value:{quantity:q}};}for (const text of ['{"quantity":3,"admin":true}','{"quantity":"3"}','{"quantity":0}']) { const input: unknown = JSON.parse(text); console.log(JSON.stringify(parseOrder(input)));}Run node --experimental-strip-types main.mts in a disposable directory with the files shown. Expected standard output:
{"ok":true,"value":{"quantity":3}}{"ok":false,"error":"quantity"}{"ok":false,"error":"quantity"}An experimental warning is expected on stderr for this local version.
Check independently with tsc --strict --noEmit --target es2022 --module nodenext --allowImportingTsExtensions main.mts.
How it works
Check object shape, null, array status and field types before constructing a new DTO (data transfer object). A safe integer and a bounded quantity are separate rules. Returning only approved fields prevents accidental propagation of extra client fields. A validator checks data, not permission to access a resource. Malformed JSON needs a separate parse-error boundary. The local example uses fixed input and an explicit union; the compiler narrows based on the ok discriminator.
Common mistake
Avoid JSON.parse(text) as Order. The assertion changes the compiler’s view only. It never rejects negative values or unauthorized fields.
Practice
Add tests for null, an array and a quantity of 101. Decide whether unknown keys are ignored or rejected and document the choice.
Documentation: primary source. Candidate lookup: node-typed-api-contracts-lookup. Prerequisite: node-node-module-resolution-and-types (platform route unverified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Typed API contracts — knowledge check
Apply the lesson’s contracts and identify common boundary mistakes.
Which type is appropriate before checking external input?
Why construct a new value with just quantity?
Does the validator prove the caller owns the order?