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.
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.
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.
npm init -y
npm install -D typescript tsx @types/node
npx tsc --init
npx tsx hello.tsconst name: string = "Ada";
console.log("Hello, AI! Welcome to TypeScript, " + name + ".");tsx runs TypeScript instantly; tsc type-checks and compiles to JavaScript.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.
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);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.
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"));Functions and generics
Type parameters and return values. Generics let one function work for many types while keeping type safety.
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);Arrays, maps and objects
Arrays have typed methods like map, filter and reduce. Map and Record hold key-value data.
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"));Async, await and errors
Network calls return a Promise. Mark functions async and await results; wrap calls in try/catch to handle failures.
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);
}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
Gradient descent from scratch
Learn y = 3x + 0.5 with plain loops: the core idea behind every neural network.
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.50Build 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.
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.
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.TypeScript learning roadmap
Tick items off as you go. Your progress is saved in this browser.
Beginner
Intermediate
Advanced
Projects to build
TypeScript cheat sheet
| Task | Syntax |
|---|---|
| Variable | let x: number = 1 |
| Union type | string | number |
| Interface | interface P { a: string } |
| Generic | function f<T>(x: T): T |
| Async | const r = await fetch(url) |
| Non-null | value! |
Common mistakes
- Using
anyeverywhere switches off the type checker; preferunknownand narrow it. - Types disappear at runtime: validate external JSON with a library like Zod.
- Forgetting
awaitgives you aPromiseinstead of the value.
Where to go next
- TypeScript Handbook — official guide
- Vercel AI SDK — agents and streaming
- Total TypeScript — free tutorials
On TensorCore.si: JavaScript volume, How AI works.
Keyboard: [ previous language · ] next language · / search the library