Vibe Coding Advanced / Owned practice and prerequisite bridges

Read TypeScript at a runtime boundary

Lesson 3 of 32. Open to read. No account needed.

A generated function can pass the TypeScript compiler and still accept an invalid request. The compiler reasons about the types described in your source; incoming JSON is a runtime value. An assertion can tell the compiler to trust that value without inspecting it. To review an AI edit, you need to identify which statements actually run and reject bad input.

You will read a typed booking, compare source with emitted JavaScript, and run an assertion and a guard on the same inputs. Then you will check the real app's HTTP boundary and repair a small equipment-input function in an isolated bridge. Keep the predictions, failures, source change and results as A03.

Checking and running happen at different times

Static checking examines source before execution. Emission produces JavaScript from that source. Runtime validation executes conditions against an actual value. TypeScript annotations and as assertions are erased during emission; ordinary JavaScript branches such as if and typeof remain.

TypeScript source goes through the pinned compiler to emitted JavaScript. Incoming JSON arrives separately at execution, where remaining object, string and supplied-ID checks decide whether to accept it.

Follow the upper arrows from source to compiler to JavaScript. In this project, noEmitOnError: true prevents new emission when the compiler reports an error. It leaves any older JavaScript files in place. The right lower arrow carries code into execution; the left lower arrow carries incoming JSON. That JSON did not pass through the source compiler. The guard's executable checks must inspect it. The diagram does not depict a type firewall or an ownership decision.

The TypeScript handbook documents assertions and their erasure. The examples below are original supplied code; you will verify their emitted form and actual results with the pinned compiler rather than infer runtime correctness from that documentation.

Read the booking contract from known JavaScript

This is the actual Booking type in src/contracts.ts, an excerpt rather than a replacement for the whole file:

export type Booking = {
  id: string;
  memberId: string;
  equipmentId: string;
  slotId: string;
  status: 'active' | 'cancelled';
};

The object type names five required properties. string describes their values for the checker. The union 'active' | 'cancelled' allows either literal string for status; it does not allow every string. export type makes that description available to other TypeScript modules. It creates no booking and does not read a request or database.

The supplied bridges/type-boundary.ts imports it with import type { Booking } from '../src/contracts.js';. A type-only import is used by the checker and erased from emitted JavaScript. The .js specifier follows the project's NodeNext module configuration; TypeScript resolves the matching source contract. Do not rename imports or change module settings to work around an unrelated diagnostic.

In that bridge, sampleBooking: Booking gives a normal object literal a checked contract. Its equipment is drill-01, slot is slot-pm and status is active. These are synthetic local values; this sample is not inserted into SQLite. The bridge also contains this complete function:

export function describeBooking(booking: Booking): string {
  return `${booking.equipmentId} / ${booking.status}`;
}

The parameter annotation describes the expected input, and : string describes the return value. The body is ordinary JavaScript property access and a template string. In the emitted file it becomes:

export function describeBooking(booking) {
    return `${booking.equipmentId} / ${booking.status}`;
}

The annotations disappear; the formatting work remains. The sample produces drill-01 / active. Calling this JavaScript with arbitrary JSON does not cause an automatic Booking check. Likewise, as Booking on a database result tells the checker what to assume; it does not itself verify the row's fields.

An assertion makes a promise; a guard examines a value

unknown means a value may have any shape, but you must establish its usable shape before accessing properties. In this exercise it represents data read from JSON. Here is the actual assertion example in bridges/type-boundary.ts:

type SlotInput = { slotId: 'slot-am' | 'slot-pm' };

export function assertedSlot(value: unknown): string {
  const body = value as SlotInput;
  return body.slotId.trim();
}

The assertion tells the checker to treat value as a SlotInput. It neither parses nor tests it. The emitted body is simply const body = value; followed by return body.slotId.trim();. A missing property can cause an incidental JavaScript error; an unlisted string still has .trim() and is returned. Whitespace padding is silently removed. None of that enforces the declared two-ID contract.

Compare the supplied runtime guard, also a complete function:

export function guardedSlot(value: unknown): string {
  if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('Expected an object');
  const body = value as Record<string, unknown>;
  if (typeof body.slotId !== 'string') throw new Error('Expected slotId string');
  if (!['slot-am', 'slot-pm'].includes(body.slotId)) throw new Error('Choose a supplied slot ID');
  return body.slotId;
}

The first branch rejects null, primitives and arrays. JavaScript considers null and arrays to have typeof equal to object, so the additional tests matter. After this branch, Record<string, unknown> lets the checker treat the value as an object with named fields of unknown type. That assertion still does not establish a valid slotId: the next typeof branch does the string check. The final membership branch accepts only the two supplied IDs. It returns the unchanged string, deliberately rejecting padded IDs instead of normalizing them. The narrowing reference explains how executable branches also refine the checker's view of a value.

This small function examines only slotId; other fields are outside its contract. It does not check booking ownership, an existing row, HTTP content type or every API field. A successful shape/ID check cannot grant permission. The application keeps those decisions at their relevant boundaries.

Prepare the isolated bridge

Finish L02's request trace first and keep A01/A02, source identities and your databases. Use the L01 reference profile: macOS arm64, Node 24.19.0, pnpm 11.25.0, TypeScript 6.0.3 and the locked dependencies. Materialization requires CPython 3.12/POSIX; the checked author profile uses CPython 3.12.14. Other platforms and fresh external tool installation remain unverified. No AI service/account or cloud resource is required here.

The lesson-03-v1 booking-workbench.zip snapshot adds six native inputs to L02: the bridge source/config/cases, tools/type-bridge.mjs, contracts/type-boundary.md and blank records/type-boundary.json. It has 32 native files / 34 archive entries. Later snapshots may add inputs; record the actual version/count. If these files are missing, verify the current Practice files checksum and use L01 to materialize/install/build/check in a new absent owned destination. Preserve your older copy and A02; do not merge over edits.

All shell commands below run in the materialized native project root. Open records/type-boundary.json and record actual paths, payload/source identity and prior A02 location. It is a blank learner card, not evidence of a pass. The fixtures in bridges/boundary-cases.json are deterministic authored values, not model outputs. The only intended source edit is in the isolated bridge; leave application src/, policy and schema unchanged.

Verify the compiler and existing app first:

pnpm exec tsc --version
pnpm run typecheck

The compiler must report Version 6.0.3. pnpm exec uses the project's installed compiler; it is not an instruction to download an unpinned latest package. typecheck checks the app's tsconfig.json without emitting. This baseline config includes src/**/*.ts; it does not include the new bridge.

The actual bridges/tsconfig.json is:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "rootDir": "..",
    "outDir": "../data/type-boundary-build"
  },
  "include": [
    "type-boundary.ts",
    "../src/contracts.ts"
  ]
}

It inherits strict checking, NodeNext resolution and noEmitOnError: true from the app configuration. Its paths are relative to this config: rootDir is the native root, covering the bridge and imported contract. Output preserves that relative structure under data/type-boundary-build/, separate from app dist/. These commands first check that specific project, then emit it:

pnpm exec tsc -p bridges/tsconfig.json --noEmit
pnpm exec tsc -p bridges/tsconfig.json
node tools/type-bridge.mjs observe

-p selects the bridge config. --noEmit performs checking only; the next line must succeed to produce current JavaScript. Inspect data/type-boundary-build/bridges/type-boundary.js in your editor. Locate the erased import/type/annotations/assertions and the remaining runtime branches. The compile also emits the imported contracts module, which has no runtime booking object. Do not edit emitted files; subsequent builds replace them. These operations write only the bridge's output directory and print local fixture observations. They do not write bookings or contact a model.

Before reading the observe results, predict the eight slot cases. It prints the input, contract expectation and actual assertion/guard results. It exits zero when observation completes, even when the assertion behaves incorrectly.

Input groupAssertion result to explainGuard result
Exact morning/afternoon IDReturns the same IDAccepts unchanged
Missing field or numberIncidental .trim() errorDeliberate string rejection
slot-nightReturns unlisted stringDeliberate supplied-ID rejection
" slot-pm "Trims and accepts itDeliberate supplied-ID rejection
null or arrayIncidental property/method errorDeliberate object rejection

Record your actual errors rather than copying an engine's wording from another version. Controlled guard messages come from the supplied function. An unexpected TypeError is a runtime failure, not proof of intentional input validation.

Guided experiment: keep an old build visible

Save the good source/check results. In only bridges/type-boundary.ts, change sampleBooking's status: 'active' to status: 'pending'. Keep the failed variant or diff in your A03 evidence. Run the actual emitting build:

pnpm exec tsc -p bridges/tsconfig.json

Expect a nonzero exit and a diagnostic like this illustrative excerpt:

error TS2322: Type '"pending"' is not assignable to type '"active" | "cancelled"'.

Location/format can vary; inspect the actual source path and diagnostic. The checker rejects that typed literal. Because the inherited noEmitOnError is true, the older emitted JavaScript remains unchanged; it can still contain status: 'active'. The option reference describes emission suppression, not deletion of old output. Do not call the old runtime result a pass for the new failed source.

Restore that one field to active, retaining your failed evidence, and rebuild successfully. Do not weaken the union, add as Booking, turn off strict checks or delete build folders to make the diagnostic disappear. You want to understand the contract and build identity, not hide the conflict.

Connect it to the real JSON boundary

In src/server.ts, readObject is an async function returning Promise<Record<string, unknown>>. A promise represents a result available after asynchronous work. await readObject(req) waits for request-body reading; a rejection reaches the handler's error path. Neither async nor the return annotation validates the bytes. The executable code checks content type/size, parses JSON, rejects non-object bodies, then returns the object with unknown field types. The create handler separately checks allowed keys, field types and whether the IDs exist in the supplied data.

Notice why return body as Record<string, unknown> in that function is narrower than a claim that the object is a valid booking. Its preceding object guard has checked one fact. The equipment/slot checks still have to execute afterwards. Similarly, Booking | undefined on store.get describes a row-or-no-row result; the cancellation handler must branch on absence and then ask its policy. These types cannot supply permission. The synthetic member selector/header remains a test input, not real login.

Use a separate new database name so this exercise cannot reset your A02 data. In terminal A, native root:

node tools/seed.mjs types-03.sqlite
node tools/inspect.mjs types-03.sqlite
node tools/start.mjs types-03.sqlite 0

Retain the inspector's full path and two before rows. If that name exists, preserve it and choose a new name consistently, as taught in L01/L02. Verify the start record's database, PID and assigned loopback URL. In terminal B, same root, the next block is a template: replace the port placeholder with the actual number from terminal A before executing:

VIBE_URL='http://127.0.0.1:REPLACE_WITH_YOUR_PORT'
node tools/type-bridge.mjs http "$VIBE_URL"
node tools/inspect.mjs types-03.sqlite

The tool sends eight real POSTs as synthetic member-a: missing slot, number slot, unlisted slot, extra body owner, malformed JSON, null, array and wrong content type. Expect seven 400 responses and one 415 for text/plain. It prints each actual body/status/error and its comparison with the fixed case. Do not treat it as a browser capture or silently change expected results.

All eight should be rejected before creation; compare the direct after rows with the same file's before rows. They must be unchanged. A runtime input with slotId: 17 reaches these checks regardless of a TypeScript caller's declared type. The supplied client restricts the origin, follows no redirect and times out each exchange after five seconds. You must still establish ownership from the start record; another loopback listener is not automatically yours.

Independent variation: guard an equipment input

Attempt this before opening the solution. In bridges/type-boundary.ts, change only candidateEquipment. It currently asserts a two-ID equipment type and calls .trim() without validation. Its required behaviour, supplied in contracts/type-boundary.md, is:

  • Accept a non-null, non-array object with equipmentId exactly drill-01 or camera-01; return that ID unchanged.
  • Reject null/primitives/arrays with Error('Expected an object').
  • Reject missing/non-string fields with Error('Expected equipmentId string').
  • Reject other strings, including padded IDs, with Error('Choose supplied equipment').

The exact messages are a small exercise contract. They distinguish intentional branches from incidental property/method errors. They are not a general policy for production error disclosure. Other object fields remain outside this small function's contract; the real API has its separate allowed-key checks.

First record the original failure:

node tools/type-bridge.mjs check-candidate

The untouched candidate should report 2 of 8 cases matching and exit 1. That is an expected exercise failure, separate from a broken baseline setup. Predict which two string cases it wrongly accepts before examining the details. After your source change, run:

pnpm exec tsc -p bridges/tsconfig.json --noEmit
pnpm exec tsc -p bridges/tsconfig.json
node tools/type-bridge.mjs check-candidate

Require the build to succeed before interpreting the final check. --noEmit alone leaves the old candidate in place even when the new source type-checks. Keep your diff, failed output and actual after results in A03. Do not edit the case expectations or emitted file. Both valid IDs must keep working; simply throwing for every input does not meet the contract.

Hint 1: Apply checks in the order object, field type, membership. Hint 2: The slot guard supplies the pattern, but the property, allowed IDs and messages must match the equipment contract. .trim() changes the accepted input language.

Explained solution after your attempt

This is one complete replacement for candidateEquipment in the bridge source:

export function candidateEquipment(value: unknown): string {
  if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('Expected an object');
  const body = value as Record<string, unknown>;
  if (typeof body.equipmentId !== 'string') throw new Error('Expected equipmentId string');
  if (!['drill-01', 'camera-01'].includes(body.equipmentId)) throw new Error('Choose supplied equipment');
  return body.equipmentId;
}

The object branch prevents property access on null or an unsuitable shape. The field-type branch prevents a missing/number field from reaching string use. The membership branch rejects unlisted/padded strings without normalization. Only the final return accepts a value. The as Record assertion supplies a static description after the object check; the executable checks still do the work. After a successful rebuild this version matches all eight supplied cases. Other implementations can be valid if they preserve these values/rejections and controlled messages. Eight cases are bounded evidence, not an exhaustive proof for every JavaScript value or production request.

Answer in your own words: why can a value pass an assertion and remain invalid at runtime? The assertion changes the checker's assumptions and is erased. It executes no check of JSON or ownership. Show the unlisted-string observation and one emitted guard branch as evidence, rather than repeating the definition.

Diagnose, retain and stop

ObservationSafe interpretation and next step
Compiler version differs or inputs are missingStop; verify the pinned installed tools and current payload. Preserve old workspace/A02 and use a new destination for a required snapshot.
App typecheck passes but bridge edit is uncheckedIt includes src, not the bridge. Use -p bridges/tsconfig.json.
Build fails but old JS still runsKeep the diagnostic/source identity. Correct the source and rebuild; old output cannot accept the new source.
Type check succeeds but candidate still fails as before--noEmit does not rebuild. Inspect the emitted path and require a successful emitting command.
Candidate gets wrong-ID cases green by trimmingThe contract rejects padded/unlisted IDs. Keep expected cases and implement membership without silent normalization.
HTTP status or direct rows differKeep the actual result. Match current URL, database path and source/build before diagnosing; do not reset/migrate data or edit policy.

A03 should link source and emitted identities, predictions/actual slot results, the invalid-status diagnostic, the restored good build, HTTP/direct-row evidence, and the independent before/change/build/after sequence. Preserve failures and unknowns. Keep A01/A02/A03, bridge source and observations, app source and named databases. Do not broadly delete build folders or overwrite unrelated edits to recover; compare with a separate verified payload/native copy if needed.

In terminal A, Ctrl-C only this verified listener and wait for STOPPED: owned app closed; source and database retained. unset VIBE_URL clears only the terminal string. The bridge does not start a persistent process. No model, external service or billable resource needs cleanup. Keep emitted observations for explanation, while treating source plus a successful build as the basis for subsequent execution.

27 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy