Index Ai Academy
Phase 8 · JavaScript

Modules, Node and reading TypeScript

import and export, package.json, classes, and types as notes the compiler checks, read through a small tool server.

About 30 minutes · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

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
Quick check
A Python programmer opens a file that begins import { z } from "zod"; and has function area(w: number, h: number): number. What are the : number parts?
  1. Runtime checks that raise an error when a value has the wrong type
  2. Python-style default values
  3. Comments the compiler ignores
  4. Notes about types, checked before the program runs and then removed
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.

Try it now

The import names the file as ./tools.js, even though the source is tools.ts: it names the JavaScript the compiler will write.

Quick check
Recall: in JavaScript, what is "2" + 1?
  1. 3
  2. A TypeError
  3. "21"
  4. "3"
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.

In your own words
In your own words: what are export, import and package.json for, and what happens to types when TypeScript 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.

Quick check
A function is declared function ship(order: Order | undefined): string. Which call does the compiler accept?
ship(undefined);
ship(null);
ship(42);
ship("TENT");
  1. Only ship("TENT")
  2. All four
  3. ship(null) and ship(undefined), since both mean empty
  4. ship(undefined) only, since the others are not an Order or undefined
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[].

Quick check
What does this print?
const block = { type: "text", text: "Hi" };
console.log(block.type === "tool_use" ? block.name : "no tool", Object.keys(block));
  1. no tool []
  2. A TypeError
  3. undefined [ 'type', 'text' ]
  4. no tool [ 'type', 'text' ]
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.

Worked example

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"));
In the lesson you can change this and run it.

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.

Quick check
What does this print?
const stock = { "TENT-2P": 4, "MUG-01": 0 };
console.log(stock["MUG-01"] ?? 9, stock["LAMP-1"] ?? 9, stock["MUG-01"] || 9);
  1. 0 9 9
  2. 9 9 9
  3. 0 undefined 9
  4. 0 9 0
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.

Drill

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);
In the lesson, your code is checked as you write it.
Drill

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" } }));
In the lesson, your code is checked as you write it.

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.

In your own words
In your own words: how does a union type tell two shapes apart, and why do types not protect you from outside data?

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.

Quick check
In the tool server, the handler is async ({ sku }) => { ... }. What does ({ sku }) do?
  1. Makes the handler run twice
  2. Pulls the sku field out of the input object into a name
  3. Declares that sku is a function the handler will call
  4. Renames the tool to sku
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.

In your own words
In your own words: which parts of the TypeScript tool server match parts of a Python MCP server?

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?

  1. Checks it, then removes it
  2. Turns it into a run-time check
  3. Leaves it in, for the browser to read
  4. Converts the value to a number

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

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
  1. HTTP from the wire up FreeWhat really travels between client and server: bytes, headers and bodies.40 min
  2. API stylesREST, RPC, GraphQL, gRPC and streaming: what each is for.35 min
  3. Build an API server from scratchRouting, handlers and responses, with no framework.45 min
  4. A web framework, from the insideDecorators, middleware and error handling: how Flask and FastAPI work.40 min
  5. Designing a REST APIResources, methods, status codes, errors and pagination done well.45 min
  6. Validating requests with schemasCheck every request against a JSON Schema and say exactly what's wrong.45 min
  7. A database-backed APICRUD endpoints on SQLite, with safe concurrent updates.45 min
  8. Authentication and authorizationAPI keys, sessions, tokens and OAuth: who's calling, and what may they do?45 min
  9. Rate limits, retries and idempotencyKeep an API up under load and make retries safe.45 min
  10. Async HTTP clientsMany requests at once with asyncio and httpx: limits, timeouts and retries.45 min
  11. Webhooks and eventsPush events to other systems: signed, retried and deduplicated.45 min
  12. Documenting APIs with OpenAPIA machine-readable contract for docs, SDKs and AI tools.40 min
  13. Running APIs in productionVersioning, CORS, caching, request ids and health checks.45 min
  14. Project: a reviews APIAn authenticated, validated, paginated API with tests.45 min
  15. Web pages with FlaskRoutes, Jinja templates, a shared layout, links and error pages, tested with the test client.45 min
  16. Forms and redirectsGET and POST, validation messages, post/redirect/get, flash messages and CSRF tokens.45 min
  17. Accounts and loginsPassword hashing with bcrypt, sessions, pages that need a login, and safe logout.45 min
  18. Project: a trail log web appA multi-page app with a database, accounts, forms and tests.45 min
  19. JavaScript for Python programmersVariables, functions, arrays and objects mapped from Python, and the traps: truthy empty arrays, for...in and string sort.35 min
  20. Async JavaScript: promises, await and fetchThe event loop, async and await, fetch with res.ok checks, Promise.all, and timeouts with AbortController.35 min
  21. 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
  22. 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
  23. APIs with FastAPITyped routes, pydantic models, automatic validation and docs, tested with httpx.45 min
  24. 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
  25. Project: a FastAPI service with accountsA session per request, bcrypt sign-ups, signed tokens, ownership checks and tests on a fresh database.45 min
  26. 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
  27. 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