bhylu.com

Advertisements

TypeScript Arrays

An array type describes its elements, not a guaranteed length. With strict indexed access, reading a position gives a possible undefined unless the access is known to be safe.

How it works

A shelf keeps numeric packet counts. Iteration is often clearer than indexing when you only need each value. reduce has an explicit starting total, so an empty shelf list produces zero rather than an exception. The array’s type prevents inserting text, but it does not prevent negative counts, mutation during a workflow or an index outside the current length.

Run the code

Try in playground loads this source without running it. Choose Run when ready. The existing TypeScript 5.8.3 worker transpiles and executes one file; it does not perform full semantic type checking, load npm imports or provide DOM/Node APIs. Use the local compiler for the type contract.

For a full check, save the three downloads together in a new folder, run npm install, then npm run check. Use npm run build followed by npm start to execute the checked JavaScript with Node. The supplied project enables strict checking, indexed-access checks and exact optional properties.

Example

lesson.ts

const counts: number[] = [4, 7, 3];
const total = counts.reduce((sum, count) => sum + count, 0);
console.log(total);
console.log(counts[9] ?? "Missing shelf");

Expected result

14
Missing shelf

The accumulator starts at zero and adds three values. The second line demonstrates an absent position deliberately; the nullish fallback handles it without claiming the array has ten items. Validate counts when creating the list if later calculations depend on non-negative integers.