TypeScript Cheatsheet

Quick reference for TypeScript basics — structures, functions, loops, and async patterns.

Data Structures

Structure Syntax Notes
Array number[] / Array<T> Ordered
Tuple [string, number] Fixed length & types
Map Map<K, V> Key-value
Set Set<T> Unique values
Object { key: string } Structured data

Functions

// Basic function
function greet(name: string): string {
    return `Hello, ${name}`;
}

// Arrow function
const square = (x: number): number => x * x;

// Optional & default params
function connect(host: string = "localhost", port?: number): string {
    return `${host}:${port ?? 3000}`;
}

// Generic function
function first<T>(arr: T[]): T | undefined {
    return arr[0];
}

// Rest parameters
function sum(...nums: number[]): number {
    return nums.reduce((a, b) => a + b, 0);
}

Loops & Iteration

// for
for (let i = 0; i < 5; i++) {
    console.log(i);
}

// for...of
for (const item of [1, 2, 3]) {
    console.log(item);
}

// for...in (keys)
for (const key in { a: 1, b: 2 }) {
    console.log(key);
}

// Array methods
const doubled = [1, 2, 3].map(n => n * 2);
const evens = [1, 2, 3, 4].filter(n => n % 2 === 0);
const sum = [1, 2, 3].reduce((a, b) => a + b, 0);

Async & Concurrency

// Promise
const fetchUser = (id: number): Promise<string> =>
    new Promise(resolve => setTimeout(() => resolve(`User ${id}`), 100));

// async/await
async function main(): Promise<void> {
    const user = await fetchUser(1);
    console.log(user);
}

// Promise.all (parallel)
const results = await Promise.all([
    fetchUser(1), fetchUser(2)
]);

// Promise.allSettled
const settled = await Promise.allSettled([
    fetchUser(1), fetchUser(2)
]);

// AbortController (cancellation)
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);