TypeScript

Runtime validation of typed API contracts

Treat parsed external JSON as unknown until its structure has been checked. A discriminated union can represent either accepted data or a useful validation error, allowing callers to handle both outcomes explicitly. 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. Avoid `JSON.parse(text) as Order`. The assertion changes the compiler’s view only. It never rejects negative values or unauthorized fields. Evidence: Actual TypeScript source execution, independent tsc check. Source: https://nodejs.org/download/release/v22.16.0/docs/api/typescript.html

Formal Syntax & Structure

nodejs syntaxnodejs
See example for the scoped contract

Working Example

Example Snippetnodejs
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)));}
Node.js Reference