Modules, Node and reading TypeScript
import and export, package.json, classes, and types as notes the compiler checks, read through a small tool server.
What it covers6
Why it matters
You will read more TypeScript than you write. SDK examples, MCP servers and front-end code are often TypeScript, and a Python programmer who can read it can use all of them. The good news is that TypeScript is JavaScript with notes written beside the names: the notes say what kind of value each name holds, a checker reads them before the program runs, and then they are removed. This lesson teaches reading: modules, a package file, classes, and the types you will see most, ending on a small tool server that you map line by line to the Python one you met in the MCP phase.
What you'll be able to do
- Read import and export, and say what a package.json tells Node about a project
- Write a class with a constructor, a method and a getter, and read one in TypeScript
- Read types as notes the compiler checks: unions, optional fields and generics
- Read a 30-line TypeScript tool server and say which line does what
import { z } from "zod"; and has function area(w: number, h: number): number. What are the : number parts?Show the answer
Notes about types, checked before the program runs and then removed
They are TypeScript type annotations. A checker reads them before the program runs, and then they are removed, so the JavaScript that runs has none of them.
The idea: JavaScript, with notes beside the names
This rests on JavaScript for Python programmers, which mapped Python to JavaScript, and Async JavaScript: promises, await and fetch, whose await and fetch appear in every TypeScript example. A project of several files needs three things Python gives you with import, a package manager and a type checker. In JavaScript the first is modules: a file that writes export function f() {} offers f, and another that writes import { f } from "./tools.js" takes it. The second is package.json, a file at the project's root that names the project and its dependencies, and, with "type": "module", tells Node that its files use import. npm install reads it, as pip install -r requirements.txt does. The third is TypeScript: you write name: string beside a name, the compiler checks that every use agrees, and a file ending .ts becomes plain JavaScript with the notes removed. The picture shows three files of a small project. A small project also rewards a few habits: read the package.json first, since it names the entry file and the commands, and look for a tsconfig.json, which sets how strictly the compiler checks, so a project with strict settings rejects code that a lax one would accept.
The import names the file as ./tools.js, even though the source is tools.ts: it names the JavaScript the compiler will write.
"2" + 1?Show the answer
"21"
+ joins as soon as one side is text, so the number is turned into text and joined: "21". TypeScript's types exist to catch this kind of slip before the program runs.
Write a sentence or two, then compare it with a good answer in the lesson.
In JavaScript: classes, and types as notes
A class groups data with the functions that use it, as in Python. The differences to read past: the constructor is called constructor, not __init__; the instance is this, not self, and you must write it; a name starting with # is private; and get value() makes a property that is computed when read. Run the cell, then change the numbers.
class Cart { #items = []; constructor(owner) { this.owner = owner; } add(sku, qty = 1) { this.#items.push({ sku, qty }); return this; } get count() { return this.#items.reduce((n, item) => n + item.qty, 0); } } const cart = new Cart("ana").add("TENT").add("MUG", 2); console.log(cart.owner, cart.count);
add returns this, so calls chain. count is read without parentheses, because it is a getter.
Now the same shape with the notes TypeScript adds. This block is shown, not run: the page runs JavaScript. Read the notes, and read what each protects.
class Cart { #items: { sku: string; qty: number }[] = []; constructor(public owner: string) {} add(sku: string, qty: number = 1): this { this.#items.push({ sku, qty }); return this; } get count(): number { return this.#items.reduce((n, item) => n + item.qty, 0); } }
{ sku: string; qty: number }[] is an array of objects with those two fields, public owner: string declares and sets the field in one go, and : number after the parentheses says what add and count return. With these notes, cart.add(42) is a compile error: 42 is not a string.
function ship(order: Order | undefined): string. Which call does the compiler accept?ship(undefined); ship(null); ship(42); ship("TENT");
Show the answer
ship(undefined) only, since the others are not an Order or undefined
The parameter is an Order or undefined. null is a different value, 42 is a number, and "TENT" is a string, so only ship(undefined) and a real Order are accepted.
Unions you will see every day
The type you will meet most is the union, a value that is one of several shapes. A reply's content is a list of blocks, and a block is either a text block or a tool call, told apart by one field. Read this and the cell after it together: the type is a note, and the if in the cell is the same check, made while the program runs.
type Block = | { type: "text"; text: string } | { type: "tool_use"; name: string; input: Record<string, unknown> };
const blocks = [ { type: "text", text: "Let me look that up." }, { type: "tool_use", name: "get_stock", input: { sku: "MUG-01" } }, ]; for (const block of blocks) { if (block.type === "text") { console.log("text:", block.text); } else { console.log("tool:", block.name, JSON.stringify(block.input)); } }
Inside if (block.type === "text") the compiler knows block.text exists, and in the else it knows block.name does. That is called narrowing. Two more notes appear everywhere: ? after a name means optional (input?: string), and <T> marks a generic, a type that takes a type, so Promise<string> is a promise of a string and Array<number> is number[].
const block = { type: "text", text: "Hi" };
console.log(block.type === "tool_use" ? block.name : "no tool", Object.keys(block));Show the answer
no tool [ 'type', 'text' ]
The type is "text", so the test is false and the else side runs. block.name is never read. In TypeScript the compiler narrows the type inside each branch, so reading .name on the text side would be an error.
Group items by their first letter with a Map
A Map is JavaScript's dictionary with any key type. In TypeScript it is written Map<string, string[]>: a map from strings to arrays of strings.
const groups = new Map(); for (const word of ["tent", "tarp", "mug", "map"]) { const key = word[0]; groups.set(key, [...(groups.get(key) ?? []), word]); } console.log([...groups]); console.log(groups.get("t").length, groups.has("z"));
groups.get(key) ?? [] is groups.get(key, []): a missing key gives an empty array to extend. The spread [...] copies it and adds the word, as Python's groups.get(key, []) + [word] would. The map ends with two keys: t has two words and m has two.
const stock = { "TENT-2P": 4, "MUG-01": 0 };
console.log(stock["MUG-01"] ?? 9, stock["LAMP-1"] ?? 9, stock["MUG-01"] || 9);Show the answer
0 9 9
?? replaces only undefined and null, so a real 0 stays 0, and the missing key becomes 9. || replaces every falsy value, so 0 becomes 9 too. That is why the tool server writes ?? 0.
A class with a getter
Write the class Basket: add(sku, qty = 1) adds a line and returns this; remove(sku) deletes every line with that sku and returns this; the getter count is the total quantity. Keep the lines in a private #lines array.
class Basket { #lines = []; add(sku, qty = 1) { return this; } remove(sku) { return this; } get count() { return 0; } } const b = new Basket().add("TENT").add("MUG", 2).remove("TENT"); console.log(b.count);
Read a block by its type
Write describe(block): for a block with type text return text: <its text>; for type tool_use return tool: <name>(<the keys of input, joined by commas>); for anything else return the word unknown.
function describe(block) {
return "unknown";
}
console.log(describe({ type: "text", text: "Hi" }));
console.log(describe({ type: "tool_use", name: "get_stock", input: { sku: "M" } }));Writing a type guard, in JavaScript
A TypeScript type protects you from your own mistakes, not from the world: data from a model or a network is whatever it is, and the notes are gone at run time. So code that reads outside data still checks it. A type guard is a function that does that check. The exercise below is one.
Write a sentence or two, then compare it with a good answer in the lesson.
In AI and ML systems: reading a tool server
An MCP server is a program that offers tools to a model, and the SDK's examples are often TypeScript. This one is about thirty lines. Each idea is one you know from Python, with different spellings, and Build a server: tools builds the same server in Python. Read it from the top and say, for each line, what it does.
async ({ sku }) => { ... }. What does ({ sku }) do?Show the answer
Pulls the sku field out of the input object into a name
It is destructuring: the handler receives one object, and { sku } takes its sku field into a local name. It is the same as async (input) => { const sku = input.sku; ... }.
Where this shows up in an engineer's week
Three situations. Copying an SDK example and wanting to know what ! after a name means (it tells the compiler "trust me, this is not undefined"). A type error you did not expect when a function that returns string | undefined is used as a string, which is the compiler catching a real bug. Reading a front end that renders a model's reply, whose types describe the blocks. In each, the types are a map of what the code expects. Goes deeper in: Build a server: tools writes this server in Python, The same server with the official SDKs uses the official SDKs, and A chat front end in the browser reads a reply in a page.
Write a sentence or two, then compare it with a good answer in the lesson.
Practice what you just read
- 1 code example you can edit and run
- a practice exercise that checks your code
- a 5-question quiz
- 9 review cards for spaced repetition
Try a quiz question
What does TypeScript do to a type annotation such as : number before the program runs?
Before this lesson
Where this lesson leads.
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Phase 8 · about 23 hours of study
APIs
Design, build, secure and scale web APIs from first principles
27 lessons 1 free
- HTTP from the wire up FreeWhat really travels between client and server: bytes, headers and bodies.40 min
- API stylesREST, RPC, GraphQL, gRPC and streaming: what each is for.35 min
- Build an API server from scratchRouting, handlers and responses, with no framework.45 min
- A web framework, from the insideDecorators, middleware and error handling: how Flask and FastAPI work.40 min
- Designing a REST APIResources, methods, status codes, errors and pagination done well.45 min
- Validating requests with schemasCheck every request against a JSON Schema and say exactly what's wrong.45 min
- A database-backed APICRUD endpoints on SQLite, with safe concurrent updates.45 min
- Authentication and authorizationAPI keys, sessions, tokens and OAuth: who's calling, and what may they do?45 min
- Rate limits, retries and idempotencyKeep an API up under load and make retries safe.45 min
- Async HTTP clientsMany requests at once with asyncio and httpx: limits, timeouts and retries.45 min
- Webhooks and eventsPush events to other systems: signed, retried and deduplicated.45 min
- Documenting APIs with OpenAPIA machine-readable contract for docs, SDKs and AI tools.40 min
- Running APIs in productionVersioning, CORS, caching, request ids and health checks.45 min
- Project: a reviews APIAn authenticated, validated, paginated API with tests.45 min
- Web pages with FlaskRoutes, Jinja templates, a shared layout, links and error pages, tested with the test client.45 min
- Forms and redirectsGET and POST, validation messages, post/redirect/get, flash messages and CSRF tokens.45 min
- Accounts and loginsPassword hashing with bcrypt, sessions, pages that need a login, and safe logout.45 min
- Project: a trail log web appA multi-page app with a database, accounts, forms and tests.45 min
- JavaScript for Python programmersVariables, functions, arrays and objects mapped from Python, and the traps: truthy empty arrays, for...in and string sort.35 min
- Async JavaScript: promises, await and fetchThe event loop, async and await, fetch with res.ok checks, Promise.all, and timeouts with AbortController.35 min
- Modules, Node and reading TypeScriptimport and export, package.json, classes, and types as notes the compiler checks, read through a small tool server.30 min
- A chat front end in the browserThe DOM and events, model text kept out of innerHTML, a streamed reply parsed from server-sent events, and a Stop button.40 min
- APIs with FastAPITyped routes, pydantic models, automatic validation and docs, tested with httpx.45 min
- Streaming from the serverServer-sent events written by a server: an ASGI app that sends a body in pieces, FastAPI's StreamingResponse, heartbeats, and what a closed connection looks like.40 min
- Project: a FastAPI service with accountsA session per request, bcrypt sign-ups, signed tokens, ownership checks and tests on a fresh database.45 min
- Serving a model behind FastAPILoad once with lifespan, a typed predict route, a batch route, a cap on work in flight, 429 with Retry-After, a readiness route and a 202 job.45 min
- Capstone: a streaming chat serviceA FastAPI service with key auth, a per-user bucket, a token budget, request ids and an event-stream reply, tested on fresh state.45 min
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write