TypeScript · Lesson 92 of 120
Node with TypeScript
Files and paths.
TypeScript is great for scripts and servers in Node. Node's modules are fully typed, so reading files, building paths, and handling arguments are all checked.

- Scripts and servers
- Typed Node modules
- Checked
A stock report script
We write a stock file, then read it back. JSON parse returns any, so we validate the shape before using it. Then we print a report. Run it.
app.tstypescript
import { writeFileSync, readFileSync } from "node:fs";
type Stock = Record<string, number>;
writeFileSync("stock.json", JSON.stringify({ Leeds: 12, York: 0, Hull: 8 }));
const raw: unknown = JSON.parse(readFileSync("stock.json", "utf8"));
const isStock = (x: unknown): x is Stock =>
typeof x === "object" && x !== null && Object.values(x).every(v => typeof v === "number");
if (!isStock(raw)) throw new Error("bad stock file");
for (const [store, count] of Object.entries(raw)) {
console.log(store.padEnd(6), count === 0 ? "SOLD OUT" : `${count} bikes`);
}Output
Leeds 12 bikes York SOLD OUT Hull 8 bikes
Summary
Node's typed modules plus validation make safe scripts. Next, the patterns quiz.
Key takeaways- node:fs
- unknown + guard
- Typed scripts
Next up: Patterns Quiz — test yourself