TSTypeScript · Lesson 10 of 10

TypeScript Cheatsheet

The type system on one page — annotations, interfaces, generics, utility types.

TypeScript
// ── Annotations ─────────────────────────
let n: number = 42;
let s: string; let b: boolean;
let ids: number[] = [1, 2];
let pair: [string, number] = ["a", 1];   // tuple
let anything: unknown;                    // safe any
function add(a: number, b: number): number { return a + b; }
const f = (x: string): void => {};

// ── Objects & interfaces ────────────────
interface User {
  name: string;
  age?: number;                 // optional
  readonly id: string;          // can't reassign
}
type Point = { x: number; y: number };   // type alias

// ── Unions & narrowing ──────────────────
type Status = "active" | "banned" | "new";   // literal union
function fmt(x: string | number) {
  if (typeof x === "string") return x.toUpperCase();
  return x.toFixed(2);          // narrowed to number here
}
// Discriminated union — the workhorse pattern:
type Result =
  | { ok: true; data: string }
  | { ok: false; error: string };
if (r.ok) r.data; else r.error;
TypeScript
// ── Generics ────────────────────────────
function first<T>(arr: T[]): T | undefined { return arr[0]; }
interface Box<T> { value: T }
function prop<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

// ── Utility types ───────────────────────
Partial<User>          // all props optional
Required<User>         // all props required
Pick<User, "name">     // subset
Omit<User, "id">       // everything except
Record<string, number> // typed map
ReturnType<typeof fn>  // a function's return type
NonNullable<T>

// ── Enums, assertions, misc ─────────────
const dir = "up" as const;          // literal, not string
const el = document.getElementById("x") as HTMLInputElement;
value!                              // assert non-null (avoid)
satisfies Point                     // check without widening

// ── tsconfig essentials ─────────────────
// "strict": true          <- non-negotiable
// "noUncheckedIndexedAccess": true
// "target": "ES2022", "module": "ESNext"