Skip to content
Volume T · The TensorCore.si Library

TypeScript

JavaScript with types, for apps that grow.

TypeScript adds static types to JavaScript, catching mistakes before your code runs. It powers VS Code, most large web apps and a growing share of AI agent frameworks such as the Vercel AI SDK and LangChain.js.

Prologue

Why learn TypeScript?

If you know JavaScript, you already know most of TypeScript. Types act as documentation your editor understands, so refactoring large codebases becomes safe.

  • Fewer bugs: type errors appear in your editor instead of in production.
  • Huge ecosystem: every npm package works, most ship with types.
  • AI agents: the Vercel AI SDK, OpenAI and Anthropic SDKs and Mastra are TypeScript-first.
Prologue

Set up and run your first program

Install Node.js 20 or newer, then add TypeScript to a project. Node 22.6+ can also run .ts files directly with type stripping.

terminal
npm init -y
npm install -D typescript tsx @types/node
npx tsc --init
npx tsx hello.ts
hello.ts
const name: string = "Ada";
console.log("Hello, AI! Welcome to TypeScript, " + name + ".");
Tiptsx runs TypeScript instantly; tsc type-checks and compiles to JavaScript.
Chapter 1

Types and inference

Annotate variables with : type, or let TypeScript infer them. const values cannot be reassigned. Use unknown instead of any when you do not know a type yet.

types.ts
let layers = 32;                 // inferred as number
const model: string = "llama3.1";
let ready: boolean = false;
const shape: [number, number] = [4096, 4096]; // tuple
let id: string | number = 7;     // union type
id = "gpt";
console.log(model, layers, shape, id, ready);
Chapter 2

Interfaces and type aliases

Describe the shape of objects with interface or type. Optional fields use ?. TypeScript checks shapes structurally: any object with the right fields fits.

interfaces.ts
interface Gpu {
  name: string;
  vramGb: number;
  tensorCores?: number;  // optional
}
type Precision = "fp32" | "fp16" | "fp8";

function describe(g: Gpu, p: Precision): string {
  return g.name + " with " + g.vramGb + " GB at " + p;
}
console.log(describe({ name: "H100", vramGb: 80 }, "fp8"));
Chapter 3

Functions and generics

Type parameters and return values. Generics let one function work for many types while keeping type safety.

functions.ts
const params = (layers: number, width: number): number => 12 * layers * width * width;

function first<T>(items: T[]): T | undefined {
  return items[0];
}
const g = first(["B200", "H200"]);   // type: string | undefined
console.log(params(32, 4096).toLocaleString(), g);
Chapter 4

Arrays, maps and objects

Arrays have typed methods like map, filter and reduce. Map and Record hold key-value data.

collections.ts
const vram: Record<string, number> = { H100: 80, H200: 141, B200: 180 };
const big = Object.entries(vram).filter(([, gb]) => gb > 100).map(([n]) => n);
const cache = new Map<string, string>();
cache.set("prompt-1", "answer");
console.log(big, cache.get("prompt-1"));
Chapter 5

Async, await and errors

Network calls return a Promise. Mark functions async and await results; wrap calls in try/catch to handle failures.

async.ts
async function getJson<T>(url: string): Promise<T> {
  const res = await fetch(url);
  if (!res.ok) throw new Error("HTTP " + res.status);
  return (await res.json()) as T;
}
try {
  const tags = await getJson<{ models: { name: string }[] }>("http://localhost:11434/api/tags");
  console.log(tags.models.map(m => m.name));
} catch (e) {
  console.error("Is Ollama running?", e);
}
Part II · AI with TypeScript

AI with TypeScript

TypeScript is the main language for AI apps on the web: chat interfaces, agents, retrieval pipelines and in-browser inference. Training usually happens in Python, but serving and orchestration are increasingly TypeScript.

The essential libraries

Vercel AI SDKStreaming, tool calling and agents for any model provider.
openai / @anthropic-ai/sdkOfficial API clients with full types.
Transformers.jsRun Hugging Face models in the browser or Node.
LangChain.jsChains, retrieval and agents.

Gradient descent from scratch

Learn y = 3x + 0.5 with plain loops: the core idea behind every neural network.

gradient.ts
const xs = Array.from({ length: 100 }, (_, i) => -1 + (2 * i) / 99);
const ys = xs.map(x => 3 * x + 0.5 + (Math.random() - 0.5) * 0.2);
let w = 0, b = 0;
const lr = 0.1;
for (let step = 0; step < 500; step++) {
  let gw = 0, gb = 0;
  xs.forEach((x, i) => {
    const err = w * x + b - ys[i];
    gw += (2 * err * x) / xs.length;
    gb += (2 * err) / xs.length;
  });
  w -= lr * gw;
  b -= lr * gb;
}
console.log(w.toFixed(2), b.toFixed(2)); // ~3.00 0.50
Part III · Build an AI agent

Build an AI agent in TypeScript

An agent is a loop: send messages and tool definitions to a model, run any tool it asks for, send the result back, repeat until it answers. This example uses a local model through Ollama's OpenAI-compatible API.

Your goal→Model plans→Tool call→Your code runs the tool→Result back to model→Final answer
agent.ts
type Msg = { role: string; content?: string; tool_calls?: any[]; tool_call_id?: string };
const tools = [{ type: "function", function: { name: "get_weather", description: "Weather for a city",
  parameters: { type: "object", properties: { city: { type: "string" } }, required: ["city"] } } }];
const getWeather = (city: string) => "It is 24°C and sunny in " + city + ".";
const messages: Msg[] = [{ role: "user", content: "Should I take an umbrella in Lahore today?" }];

for (let round = 0; round < 5; round++) {
  const res = await fetch("http://localhost:11434/v1/chat/completions", {
    method: "POST", headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ model: "llama3.1", messages, tools }),
  });
  const msg: Msg = (await res.json()).choices[0].message;
  messages.push(msg);
  if (!msg.tool_calls?.length) { console.log(msg.content); break; }
  for (const call of msg.tool_calls) {
    const args = JSON.parse(call.function.arguments);
    messages.push({ role: "tool", tool_call_id: call.id, content: getWeather(args.city) });
  }
}

Swap the URL and model name to use a hosted provider. The Vercel AI SDK wraps this loop for you with typed tools.

Run it locallyInstall Ollama, run ollama pull llama3.1, and keep it running. The code talks to its OpenAI-compatible API at http://localhost:11434/v1, so the same program also works with vLLM, llama.cpp server or a cloud API by changing the URL, model name and adding an API key.
Part IV · Your path

TypeScript learning roadmap

Tick items off as you go. Your progress is saved in this browser.

Beginner

Intermediate

Advanced

Part IV · Your path

Projects to build

Typed chat UIA web chat that streams answers from a local model.
RAG searchEmbed your notes and answer questions about them.
CLI agentA command-line agent that can read files and call tools.
Reference

TypeScript cheat sheet

TaskSyntax
Variablelet x: number = 1
Union typestring | number
Interfaceinterface P { a: string }
Genericfunction f<T>(x: T): T
Asyncconst r = await fetch(url)
Non-nullvalue!
Reference

Common mistakes

  • Using any everywhere switches off the type checker; prefer unknown and narrow it.
  • Types disappear at runtime: validate external JSON with a library like Zod.
  • Forgetting await gives you a Promise instead of the value.
Reference

Where to go next

On TensorCore.si: JavaScript volume, How AI works.

Keyboard: [ previous language · ] next language · / search the library