FreeweightsGym

TypeScript · foundations

TypeScript Foundations Cheat Sheet

TypeScript foundations

Values & types

Want Write
Immutable binding const x = 3; (default)
Reassignable let n = 0; (only when needed)
Integer division Math.floor(a / b)/ always gives decimals
Remainder a % b
Number → string String(n)
Tuple return function f(): [number, number] { return [a, b]; }

Hook: "const until it complains."

Branching

if (n < lo) return lo;        // early return: guard first, work second
if (score >= 90) return "A";  // ladders check the highest bar first
  • Always === / !== — loose == coerces ("" == 0 is true!).
  • 90 <= x <= 100 does NOT work — write x >= 90 && x <= 100.

Loops

for (let i = 1; i <= n; i++) total += i;   // count
for (const item of items) ...              // iterate values
items.forEach((item, i) => ...)            // need the index too
while (n !== 1) { ... }                    // unknown iteration count

Null & truthiness

Expression Falls back when
a ?? b a is null or undefined only
a || b a is ANY falsy: "", 0, null, undefined, NaN

Hook: "|| asks 'is it falsy?', ?? asks 'is it missing?'"count || 10 eats a legitimate 0.

Functions

function greet(name: string, greeting: string = "Hello"): string
function apply(f: (n: number) => number, x: number)  // functions are values

Collections

Want Write
Dedupe [...new Set(items)]
Sorted copy [...items].sort() (plain .sort() mutates!)
Map lookup w/ default map.get(k) ?? 0
Insert-or-update map.set(k, (map.get(k) ?? 0) + 1)
Membership map.has(k), set.has(v), arr.includes(v)

Slices & strings

s.slice(0, i)      // first i chars; works on arrays too
items.slice(-3)    // last three; clamps short inputs, never throws
s.indexOf(" ")     // -1 means not found — handle before slicing
s.padStart(2, "0") // "5" -> "05"

Hook: "Slice takes a copy, splice takes a knife."

Gotchas this level

  • .sort() sorts numbers ALPHABETICALLY: [10, 9].sort()[10, 9]. Use .sort((a, b) => a - b).
  • Number("") is 0, parseInt("12px") is 12 — validate before converting.
  • Array const doesn't freeze contents: const a = []; a.push(1) is fine.