Terminology (5)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Type erasure
- Removing type information after checking, so the running program does not have it.
- Type assertion
- Telling a checker to treat a value as a type; in TypeScript it emits no code.
- Runtime type information
- Type data a running program can inspect, such as Go’s type descriptors or C++ typeid.
- Validation
- Checking at run time that untrusted data has the shape the code expects.
- Emit
- The JavaScript tsc writes after checking.
Checking a type and checking a value
Static checking reasons about declared types before execution. Runtime validation inspects the actual value when it is available. At an external-data boundary, these jobs must meet: code needs evidence that an incoming value satisfies the assumptions later operations make about it.
TypeScript interfaces, type aliases and assertions are erased from emitted JavaScript. An assertion supplies no conversion or runtime validator. Go interface assertions, Rust Any downcasts and C++ any_cast can inspect type information retained by their particular containers; they are different operations. Comparing them requires following what information each representation keeps, rather than treating similar cast syntax as an equivalent check.
01Assertions
What does a type assertion do at run time?
A warehouse pick terminal receives marketplace orders as JSON. One feed sends quantity as text, and the next-unit reservation is wrong even though tsc accepted the code. The intake helper asserted a number without checking the value. Before storing the next batch, the team needs to know what that assertion actually supplied.
The reservation needs arithmetic, so the intake helper asks for a number. An assertion may tell a checker what to believe, or it may ask running code to check a stored type. These four forms make that difference visible.
Each reduced probe holds the string "42" and asks for a numeric type. The TypeScript and Go versions obtain the string by parsing JSON; Rust and C++ construct it directly.
raw is unknown; as number tells the checker to treat it as a number.
// A quantity arrives as JSON text, and the code asserts it is a number.
const raw: unknown = JSON.parse('"42"');
const quantity = raw as number;
console.log(`quantity + 1 = ${quantity + 1}`);
npx tsc main.ts --strict --target ES2022 --module commonjs --noEmitOnError && node main.js
The probes reduce the intake failure to a quantity and an Order object. TypeScript’s command selects ES2022 libraries/emit and keeps main.js for inspection; it stops before node on a type error. Native messages and diagnostic type names below describe the retained builds, not portable spellings. No JSON-schema library or general JSON parser is modeled by the practice harness.
02Erasure
What does the running program know about a declared type?
After the quantity bug, the intake code adds an Order interface. Does that give the stored object a runtime schema the team can inspect? Compare the names available in each reduced probe.
Order is an interface. typeof and constructor.name show what JavaScript sees.
// What does the running program know about a declared type?
interface Order {
id: number;
}
const order: Order = { id: 7 };
console.log(`runtime type: ${typeof order}, constructor: ${order.constructor.name}`);
03Boundaries
Where does untrusted data get checked?
The team moves the check to order intake. Parsed JSON starts as untrusted data: validate its required fields before storage, choose whether extras are allowed, and inspect every item in a list. TypeScript’s static checks help within the program, but assertions, any and other deliberately unsound allowances mean even checked code is not a blanket runtime guarantee.
04Practice
Finish the payload validator
The intake team uses a small shape-check harness before connecting the validator to storage. Its Order and Cart probes exercise the feed; Point and the other tiny shapes isolate error ordering. First reject a wrong declared value, then prevent undeclared fields from being forwarded, then inspect every item ID inside a list. The parser and prior repairs are supplied at each level.
The payload validator
Check what each field holds, refuse undeclared fields, then check every list element.
In the frontend The intake handler before storage Optional
This incomplete diagnostic handler is under review. It builds the proposed storage row and returns it for inspection; no database write is performed.
Try a JSON object with id: 7, quantity: "42" and admin: true. Which value reaches quantity, and which fields survive the spread? The interface supplies no runtime refusal.
interface Order { id: number; quantity: number }
export async function POST(request: Request) {
const order = (await request.json()) as Order;
const storageRow = { ...order, quantity: order.quantity + 1 };
return Response.json(storageRow);
} The diagnostic row has quantity "421" and still carries admin. request.json parses syntax; as Order does not enforce the fields or their kinds. Decide the intake contract before passing this row to storage.
Sources: Next.js: Route Handlers,SvelteKit: +server routes,TypeScript: Type assertions.
Sources
Sign in to keep your read marks on every device. Sign in
Was this helpful?