๐Ÿ”ท

TypeScript Cheat Sheet

JavaScript with a type system bolted on โ€” catches whole categories of bugs before your code ever runs, and is the default choice for most modern large-scale web frontends and backends. Copy-paste examples plus live Run/Submit exercises.

Jump to: Your first programBasic typesInterfaces FunctionsGenericsClasses ๐Ÿš€ Practice problems

Your first program

let message: string = "Hello, world!";
console.log(message);
๐Ÿ“ TypeScript compiles down to plain JavaScript โ€” the types only exist to catch mistakes before that happens.

Basic types

let age: number = 25;
let name: string = "Sam";
let isAdult: boolean = true;
let scores: number[] = [90, 85, 77];
let id: string | number = 42;   // union type โ€” id can be EITHER

Interfaces

TypeScript's core feature โ€” describing the exact shape an object must have.

interface Dog {
  name: string;
  age: number;
}

function describe(d: Dog): string {
  return `${d.name} is ${d.age} years old`;
}

Functions

function add(a: number, b: number): number {
  return a + b;
}

const multiply = (a: number, b: number): number => a * b;

Generics

Write one function that works safely with any type, without giving up type-checking.

function firstItem<T>(arr: T[]): T {
  return arr[0];
}

const n = firstItem<number>([1, 2, 3]);   // n is typed as number

Classes

class Dog {
  constructor(public name: string, public age: number) {}

  bark(): void {
    console.log(`${this.name} says woof!`);
  }
}

// const d = new Dog("Rex", 3); d.bark();

๐Ÿš€ Practice problems

Full runnable programs, type-checked and run in a real TypeScript sandbox โ€” same workspace as the other cheat sheets.

Sum an array EASY

const nums: number[] = [4, 8, 15, 16, 23, 42];
const sum = nums.reduce((a, b) => a + b, 0);
console.log(sum);

Reverse a string MEDIUM

function reverseStr(s: string): string {
  return s.split("").reverse().join("");
}

console.log(reverseStr("typescript"));

Filter with an interface MEDIUM

interface Person {
  name: string;
  age: number;
}

const people: Person[] = [
  { name: "Sam", age: 25 },
  { name: "Ana", age: 17 },
  { name: "Lee", age: 31 },
];

const adults = people.filter(p => p.age >= 18);
adults.forEach(p => console.log(p.name));

Word frequency with a Map HARD

const text = "the cat sat on the mat the cat ran";
const counts = new Map<string, number>();
for (const word of text.split(" ")) {
  counts.set(word, (counts.get(word) || 0) + 1);
}
for (const [word, n] of counts) {
  console.log(`${word}: ${n}`);
}