Roadmap › JavaScript (ES5 → ES2025) & TypeScript Basics › Module: Advanced and TypeScript
Lessons in this course (16)

16. TypeScript essentials

Intermediate★ Must knowLesson 16 of 16
ts
type Status = "pending" | "paid" | "shipped";                 // union of literal types
interface Order { id: number; customer: string; total: number; status: Status; notes?: string }

function totalPaid(orders: Order[]): number {
  return orders.filter(o => o.status === "paid").reduce((s, o) => s + o.total, 0);
}

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

// Utility types
type OrderPreview = Pick<Order, "id" | "total">;
type OrderUpdate = Partial<Omit<Order, "id">>;
type ReadonlyOrder = Readonly<Order>;
type ById = Record<number, Order>;

// Narrowing
function format(x: string | number) {
  return typeof x === "string" ? x.toUpperCase() : x.toFixed(2);
}

// unknown vs any: unknown must be narrowed before use; any disables checking
function parse(json: string): unknown { return JSON.parse(json); }

interface vs type: both describe object shapes; interfaces can be re-opened (declaration merging) and extended; types support unions, intersections, mapped and conditional types. Enable "strict": true in tsconfig.json. TypeScript types disappear at runtime — validate external data with libraries like Zod.