TypeScript Tutorial

TypeScript Examples

121 complete TypeScript programs. Compile them at /typescript/try with tsc.

121 copy-and-run snippets. Open one in Try TypeScript at /typescript/try, change a value, and run it again. Each language has its own shelf and its own editor.

Basics

Variables

const a: number = 8;
const b: number = 11;
console.log(a + b);
Related lesson →

Let vs const

let count = 0;
count += 1;
const label = "ready";
console.log(count, label);
Related lesson →

Type annotation

let year: number = 2026;
let ready: boolean = true;
console.log(year, ready);
Related lesson →

Template string

const lang = "TypeScript";
console.log(`Learn ${lang}`);
Related lesson →

String concat

const a = "Try ";
const b = "TypeScript";
console.log(a + b);
Related lesson →

String index

const word = "python";
console.log(word[0], word[word.length - 1]);
Related lesson →

Reverse string

const word = "compiler";
console.log(word.split("").reverse().join(""));
Related lesson →

Control

If else

const n = 7;
if (n % 2 === 0) console.log("even");
else console.log("odd");
Related lesson →

Else if chain

const score = 82;
if (score >= 90) console.log("A");
else if (score >= 80) console.log("B");
else console.log("C");
Related lesson →

Switch

const day = 3;
switch (day) {
  case 1:
    console.log("Mon");
    break;
  default:
    console.log("later");
}
Related lesson →

Break continue

for (let n = 0; n < 6; n++) {
  if (n % 2 === 0) continue;
  console.log(n);
}
Related lesson →

FizzBuzz

for (let n = 1; n <= 15; n++) {
  if (n % 15 === 0) console.log("FizzBuzz");
  else if (n % 3 === 0) console.log("Fizz");
  else if (n % 5 === 0) console.log("Buzz");
  else console.log(n);
}
Related lesson →

Nested loops

for (let r = 1; r <= 3; r++) {
  const row: number[] = [];
  for (let c = 1; c <= 3; c++) row.push(r * c);
  console.log(row.join(" "));
}
Related lesson →

Max of three

const a = 8, b = 11, c = 5;
console.log(Math.max(a, b, c));
Related lesson →

Leap year

const year = 2024;
const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
console.log(leap ? "leap" : "common");
Related lesson →

Containers

Array sum

const nums: number[] = [8, 11, 5];
let sum = 0;
for (const n of nums) sum += n;
console.log(sum);
Related lesson →

Array max

const nums = [4, 17, 9, 2, 13];
console.log(Math.max(...nums));
Related lesson →

2D array

const grid: number[][] = [[1, 2, 3], [4, 5, 6]];
console.log(grid[1][0]);
Related lesson →

Push to array

const nums: number[] = [];
nums.push(4);
nums.push(17);
console.log(nums.length, nums[1]);
Related lesson →

Map values

const nums = [1, 2, 3];
console.log(nums.map((n) => n * n).join(" "));
Related lesson →

Filter even

const nums = [1, 2, 3, 4];
console.log(nums.filter((n) => n % 2 === 0).join(" "));
Related lesson →

Reduce sum

const nums = [8, 11, 5];
console.log(nums.reduce((a, n) => a + n, 0));
Related lesson →

Sort numbers

const nums = [9, 2, 7, 1, 4];
nums.sort((a, b) => a - b);
console.log(nums.join(" "));
Related lesson →

Find in array

const nums = [4, 17, 9];
console.log(nums.find((n) => n === 9));
Related lesson →

Count in array

const nums = [3, 1, 3, 2, 3];
console.log(nums.filter((n) => n === 3).length);
Related lesson →

Map lookup

const scores = new Map<string, number>();
scores.set("Mia", 95);
scores.set("Kai", 88);
console.log(scores.get("Mia"));
Related lesson →

Map iterate

const scores = new Map([["Ada", 99], ["Kai", 88]]);
for (const [name, score] of scores) console.log(name, score);
Related lesson →

Set unique

const nums = new Set([3, 1, 3, 2]);
console.log([...nums].join(" "));
Related lesson →

Set has

const tags = new Set(["html", "css"]);
console.log(tags.has("html"));
Related lesson →

Tuple

const pair: [string, number] = ["Ada", 2026];
console.log(pair[0], pair[1]);
Related lesson →

Object fields

const point = { x: 3, y: 4 };
console.log(point.x, point.y);
Related lesson →

Interface object

interface User { name: string; year: number }
const u: User = { name: "Ada", year: 2026 };
console.log(u.name);
Related lesson →

Type alias

type Point = { x: number; y: number };
const p: Point = { x: 1, y: 2 };
console.log(p.x + p.y);
Related lesson →

Union type

function label(id: string | number): string {
  return "id-" + id;
}
console.log(label(7), label("ada"));
Related lesson →

Optional field

type Note = { text: string; tag?: string };
const n: Note = { text: "hi" };
console.log(n.tag ?? "none");
Related lesson →

Functions and OOP

Add function

function add(a: number, b: number): number {
  return a + b;
}
console.log(add(8, 11));
Related lesson →

Void function

function greet(name: string): void {
  console.log("Hi,", name);
}
greet("Kai");
Related lesson →

Default argument

function greet(name = "friend"): void {
  console.log("Hi,", name);
}
greet();
greet("Kai");
Related lesson →

Optional parameter

function title(name: string, honorific?: string): string {
  return honorific ? honorific + " " + name : name;
}
console.log(title("Ada"), title("Ada", "Dr"));
Related lesson →

Overload add

function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: number | string, b: number | string): number | string {
  if (typeof a === "number" && typeof b === "number") return a + b;
  return String(a) + String(b);
}
console.log(add(2, 3));
console.log(add("2", "3"));
Related lesson →

Factorial

function factorial(n: number): number {
  let result = 1;
  for (let i = 2; i <= n; i++) result *= i;
  return result;
}
console.log(factorial(5));
Related lesson →

Recursive fibonacci

function fib(n: number): number {
  if (n < 2) return n;
  return fib(n - 1) + fib(n - 2);
}
console.log([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(fib).join(" "));
Related lesson →

Arrow function

const square = (n: number) => n * n;
console.log([1, 2, 3, 4].map(square).join(" "));
Related lesson →

Generic bigger

function bigger<T extends number | string>(a: T, b: T): T {
  return a > b ? a : b;
}
console.log(bigger(3, 9));
console.log(bigger("a", "z"));
Related lesson →

Class total

class Total {
  private sum = 0;
  add(n: number): void { this.sum += n; }
  get(): number { return this.sum; }
}
const t = new Total();
t.add(4);
t.add(7);
console.log(t.get());
Related lesson →

Constructor

class User {
  constructor(private name: string) {}
  hello(): void { console.log("Hi,", this.name); }
}
new User("Ada").hello();
Related lesson →

Access private

class Vault {
  private code = 7;
  reveal(): number { return this.code; }
}
console.log(new Vault().reveal());
Related lesson →

Getter setter

class Temp {
  private c = 0;
  get celsius(): number { return this.c; }
  set celsius(n: number) { this.c = n; }
}
const t = new Temp();
t.celsius = 21;
console.log(t.celsius);
Related lesson →

Inheritance

class Animal {
  speak(): void { console.log("..."); }
}
class Dog extends Animal {
  override speak(): void { console.log("woof"); }
}
new Dog().speak();
Related lesson →

Polymorphism

abstract class Shape {
  abstract area(): number;
}
class Square extends Shape {
  constructor(private side: number) { super(); }
  area(): number { return this.side * this.side; }
}
const s: Shape = new Square(3);
console.log(s.area());
Related lesson →

Static member

class Counter {
  static count = 0;
  constructor() { Counter.count++; }
}
new Counter();
new Counter();
console.log(Counter.count);
Related lesson →

Abstract class

abstract class Logger {
  abstract write(msg: string): void;
}
class ConsoleLogger extends Logger {
  write(msg: string): void { console.log(msg); }
}
new ConsoleLogger().write("ok");
Related lesson →

Implements

interface Greeter { hello(): string }
class Host implements Greeter {
  hello(): string { return "welcome"; }
}
console.log(new Host().hello());
Related lesson →

Namespace

namespace studio {
  export function seats(): number { return 12; }
}
console.log(studio.seats());
Related lesson →

Exception

function positive(n: number): number {
  if (n < 0) throw new Error("need a positive number");
  return n;
}
try {
  console.log(positive(-1));
} catch (err) {
  console.log((err as Error).message);
}
Related lesson →

Readonly

function sumOf(nums: readonly number[]): number {
  return nums.reduce((a, n) => a + n, 0);
}
console.log(sumOf([1, 2, 3]));
Related lesson →

As const

const roles = ["admin", "guest"] as const;
console.log(roles[0]);
Related lesson →

Type assertion

const raw: unknown = "42";
const text = raw as string;
console.log(text.length);
Related lesson →

Partial type

type User = { name: string; year: number };
const patch: Partial<User> = { year: 2026 };
console.log(patch.year);
Related lesson →

Pick type

type User = { name: string; year: number; city: string };
const card: Pick<User, "name" | "city"> = { name: "Ada", city: "London" };
console.log(card.name);
Related lesson →

Record type

const scores: Record<string, number> = { Mia: 95, Kai: 88 };
console.log(scores.Mia);
Related lesson →

Library

Date stamp

const d = new Date("2026-08-19T00:00:00Z");
console.log(d.getUTCFullYear(), d.getUTCMonth() + 1);
Related lesson →

Milliseconds

const start = Date.now();
const end = start + 5;
console.log(end - start);
Related lesson →

JSON stringify

const user = { name: "Ada", year: 2026 };
console.log(JSON.stringify(user));
Related lesson →

JSON parse

const raw = '{"n":7}';
const data = JSON.parse(raw) as { n: number };
console.log(data.n);
Related lesson →

Optional chaining

type User = { city?: { name: string } };
const u: User = {};
console.log(u.city?.name ?? "unknown");
Related lesson →

Enum numeric

enum Day { Mon, Tue, Wed }
const d: Day = Day.Tue;
console.log(d);
Related lesson →

Enum string

enum Color { Red = "red", Blue = "blue" }
console.log(Color.Red);
Related lesson →

Module style export

function seats(): number {
  return 12;
}
console.log(seats());
Related lesson →

Spread array

const a = [1, 2];
const b = [...a, 3];
console.log(b.join(" "));
Related lesson →

Destructure

const user = { name: "Ada", year: 2026 };
const { name, year } = user;
console.log(name, year);
Related lesson →

Rest params

function total(...nums: number[]): number {
  return nums.reduce((a, n) => a + n, 0);
}
console.log(total(1, 2, 3, 4));
Related lesson →

Every some

const nums = [2, 4, 6];
console.log(nums.every((n) => n % 2 === 0), nums.some((n) => n > 5));
Related lesson →

Reverse copy

const nums = [1, 2, 3];
console.log([...nums].reverse().join(" "));
Related lesson →

Min max

const nums = [4, 17, 9];
console.log(Math.min(...nums), Math.max(...nums));
Related lesson →

Set from array

const words = ["a", "b", "a"];
console.log(new Set(words).size);
Related lesson →

Map from entries

const m = new Map<string, number>([["a", 1], ["b", 2]]);
console.log(m.size);
Related lesson →

Class method chain

class Box {
  constructor(public value: number) {}
  bump(): this { this.value++; return this; }
}
console.log(new Box(1).bump().bump().value);
Related lesson →

Protected field

class Base {
  protected n = 3;
}
class Child extends Base {
  show(): number { return this.n; }
}
console.log(new Child().show());
Related lesson →

User input lines

function readLine(): string {
  return "Ada";
}
const name = readLine();
console.log("Hello,", name);
Related lesson →

Comments still compile

const n = 1; // kept
/* skipped */
console.log(n);
Related lesson →

Projects

Calculator slice

function add(a: number, b: number): number { return a + b; }
function divide(a: number, b: number): number {
  if (b === 0) throw new Error("divide by zero");
  return a / b;
}
console.log(add(10, 4));
console.log(divide(10, 4));
Related lesson →

Student top score

type Student = { name: string; score: number };
const classList: Student[] = [
  { name: "Mia", score: 91 },
  { name: "Kai", score: 88 },
  { name: "Ada", score: 99 },
];
const top = classList.reduce((a, s) => (s.score > a.score ? s : a));
console.log(top.name, top.score);
Related lesson →

Bank deposit

class Account {
  constructor(private balance: number) {}
  deposit(n: number): void { this.balance += n; }
  withdraw(n: number): boolean {
    if (n > this.balance) return false;
    this.balance -= n;
    return true;
  }
  get(): number { return this.balance; }
}
const a = new Account(50);
a.deposit(20);
console.log(a.withdraw(10), a.get());
Related lesson →

Quiz score

type Q = { prompt: string; answer: string };
const quiz: Q[] = [
  { prompt: "2+2", answer: "4" },
  { prompt: "capital of France", answer: "Paris" },
];
const replies = ["4", "London"];
let score = 0;
quiz.forEach((q, i) => { if (replies[i] === q.answer) score++; });
console.log(score);
Related lesson →

Library search

type Book = { title: string; author: string; year: number };
const shelf: Book[] = [
  { title: "Emma", author: "Austen", year: 1815 },
  { title: "Pride", author: "Austen", year: 1813 },
];
console.log(shelf.filter((b) => b.author === "Austen").map((b) => b.title).join(", "));
Related lesson →

Temperature table

function cToF(c: number): number { return c * 9 / 5 + 32; }
console.log(cToF(0).toFixed(1), cToF(100).toFixed(1));
Related lesson →

Tic-tac-toe row

const board = ["X", "X", "X", "O", " ", " ", " ", "O", " "];
function winner(b: string[]): string {
  const lines = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]];
  for (const [a, c, d] of lines) if (b[a] !== " " && b[a] === b[c] && b[c] === b[d]) return b[a];
  return "-";
}
console.log(winner(board));
Related lesson →

Contact book

const book = new Map<string, string>([["Ada", "555-0100"], ["Kai", "555-0142"]]);
console.log(book.get("Ada"));
for (const name of [...book.keys()].sort()) console.log(name);
Related lesson →

Grade letters

function letter(n: number): string {
  if (n >= 90) return "A";
  if (n >= 80) return "B";
  if (n >= 70) return "C";
  return "D";
}
const scores = [91, 84, 76];
const avg = scores.reduce((a, n) => a + n, 0) / scores.length;
console.log(scores.map(letter).join(" "), avg.toFixed(1));
Related lesson →

Shopping cart

type Item = { name: string; qty: number; price: number };
const cart: Item[] = [
  { name: "Tea", qty: 2, price: 1.75 },
  { name: "Bread", qty: 1, price: 2.40 },
];
const total = cart.reduce((a, i) => a + i.qty * i.price, 0);
console.log(total.toFixed(2));
Related lesson →

FAQ: TypeScript Examples

Common questions about this page.

What is the StudyGrid TypeScript tutorial?

The StudyGrid TypeScript tutorial follows the same chapter rhythm as C++: syntax, types, input, loops, functions, classes, generics, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run typescript examples examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn typescript examples in this TypeScript TypeScript lesson (TypeScript Examples).

Is the TypeScript editor the same as Try Python or Try C++?

No. Try TypeScript type-checks with tsc at /typescript/try and shows stdout plus compiler messages. Try Python stays at /try. Try C++ stays at /cpp/try. TypeScript lessons never open those editors.

Do I need to install a compiler to learn TypeScript?

No. Open a chapter, click Try it in TypeScript, and compile in the browser. You can also download a .ts file and compile locally with tsc.

Where should I start the TypeScript tutorial?

Start at TypeScript Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open TypeScript Examples, then generics, Map, and arrow functions. Use Next at the bottom of each chapter.

Is the TypeScript tutorial free?

Yes. The TypeScript workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.