A TypeScript lab: Node.js, the compiler and a test runner
Install Node.js and TypeScript, create a strict project, run the compiler and your code, and add a test that sends real Request objects through a handler, so you can repeat the course's cases and build your own typed API on your own computer.
What you need
The labs in this course run the real TypeScript compiler in your browser, so you can finish every case without installing anything. Working on your own computer lets you keep your code, use an editor that shows errors as you type, and build and test an API of your own for the capstone.
You need:
- Node.js (the current long-term support version), which runs JavaScript and TypeScript outside the browser. It also includes the standard
Request,ResponseandURLobjects used in the course. - The developer workstation from its guide: an editor such as Visual Studio Code (it understands TypeScript out of the box), Git and a terminal.
- TypeScript, installed as a development dependency of a project, and a test runner. Node has a built-in one, and others are free.
Set it up
- Create a project folder and start a project, then install TypeScript as a development tool:
mkdir typed-api
cd typed-api
npm init -y
npm install --save-dev typescript @types/node
npx tsc --init
- Open
tsconfig.jsonand make sure strict mode is on. Check that"strict": trueis set, that"target"is a recent version such as"ES2022", and that"module"suits your setup ("NodeNext"is common). Add"include": ["src"]so the compiler looks in your source folder. - Create
src/handler.tswith a function fromRequesttoResponse:
export async function handle(req: Request): Promise<Response> {
const url = new URL(req.url);
return new Response(JSON.stringify({ path: url.pathname }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
- Run the compiler to check it, with no output files:
npx tsc --noEmit
No output means no errors.
Check that it works
Write a test next to the handler that sends a real request through it. With Node’s built-in test runner (check the Node documentation for how to run TypeScript files in your version, or compile first with npx tsc):
import test from "node:test";
import assert from "node:assert/strict";
import { handle } from "./handler.js";
test("returns the path as JSON", async () => {
const res = await handle(new Request("http://api.example.com/parcels/P1"));
assert.equal(res.status, 200);
assert.deepEqual(await res.json(), { path: "/parcels/P1" });
});
Then break the types on purpose: assign a string to a number, forget a return, pass a string where a Request is expected. Read each error, find its TS number and fix it. When you can predict an error before the compiler shows it, your lab works.
Practise safely
- Keep
"strict": true. Turning it off to make errors disappear is the habit this course exists to break. - Use
unknown, notany, for data you do not control, and narrow it before you use it. - Never put keys or passwords in the code or the repository. Read secrets from environment variables.
- Do not run code you have not read, and install only well-known packages from the official registry. Check what a package does before you add it.
- Test with invented data. If you later connect a real database or service, use a separate test account.
Go further
- Add a lint rule that forbids
anyand non-null assertions, and run it in your build. - Use a schema library to describe a request body once and derive its TypeScript type, then compare the result with the hand-written guard from the course.
- Serve your handler with a small web server or a framework you choose, and try the same tests against a real HTTP call.
- Turn on additional strict flags such as
noUncheckedIndexedAccessand fix what they reveal. - Add the tests to a continuous-integration workflow (see the DevOps course) so every change is compiled and tested.
Courses that use this lab
Other lab guides
- A virtual machine lab on your own computer
- A Linux practice machine
- A network lab with free simulators and virtual routers
- A packet-capture lab with Wireshark and tcpdump
- A network-services lab: DHCP, DNS, proxy, load balancer, time and failover
- A Windows Server and Active Directory lab
- A developer workstation: editor, Git, Python and Node
- A container and Kubernetes lab
- A monitoring lab with Prometheus and Grafana
- A security operations (SOC) practice lab
- An isolated security lab for authorised practice
- A cloud lab that cannot surprise you with a bill
- An embedded and microcontroller lab: simulators first, hardware second
- An electronics lab: simulate first, then build on a breadboard
- A Raspberry Pi lab, with or without a Pi
- A home automation lab with Home Assistant and MQTT
- An audio, video, streaming and show-control lab
- A data lab: Python, pandas and Jupyter on your own computer
- A machine learning lab: scikit-learn, notebooks and honest experiments
- An LLM lab: a free local model, embeddings and a test harness
- A web deployment lab: Git, a free host and environment settings
Software changes quickly. Menu names and version numbers may differ a little from what you see; the ideas and the check at the end of each section stay the same. Always download from the project's own website, and read the licence terms for your situation.