Forem

Thesius Code
Thesius Code

Posted on • Originally published at datanest-stores.pages.dev

JavaScript & TypeScript Reference

JavaScript & TypeScript Reference

Everything a modern JS/TS developer needs on one screen. This pack covers ES2024+ syntax with practical examples, TypeScript's type system from basics to advanced generics, DOM API methods you actually use, async patterns (Promises, async/await, AbortController), module systems (ESM vs CJS), and a utility snippet library you'll paste from daily. No fluff — just the syntax you forget and the patterns that work.

What's Included

  • ES2024+ Syntax Reference — Destructuring, optional chaining, nullish coalescing, Array/Object methods, iterators
  • TypeScript Types Deep Dive — Utility types, generics, conditional types, mapped types, template literals
  • Async Patterns — Promises, async/await, Promise.allSettled, AbortController, retry patterns
  • DOM API Cheatsheet — Selectors, events, observers, Fetch API, Web Storage, URL manipulation
  • Module Systems — ESM import/export, dynamic imports, CJS interop, package.json configuration
  • Utility Snippets — 30+ copy-paste functions for dates, strings, arrays, objects, and validation
  • Error Handling Patterns — Custom errors, Result types, error boundaries, global handlers

Preview / Sample Content

TypeScript — Essential Utility Types

// Pick only the fields you need
type UserSummary = Pick<User, "id" | "name" | "email">;

// Make all fields optional (great for update DTOs)
type UpdateUser = Partial<User>;

// Make all fields required
type CompleteProfile = Required<User>;

// Remove specific fields
type PublicUser = Omit<User, "password" | "ssn">;

// Make all fields readonly (immutable)
type FrozenConfig = Readonly<Config>;

// Create a type from union of string keys
type Theme = Record<"light" | "dark" | "system", ThemeConfig>;

// Extract return type of a function
type ApiResult = ReturnType<typeof fetchUser>;

// Extract parameter types
type FetchParams = Parameters<typeof fetchUser>;

// Conditional types — narrow based on shape
type IsString<T> = T extends string ? true : false;

// Template literal types
type EventName = `on${Capitalize<"click" | "hover" | "focus">}`;
// Result: "onClick" | "onHover" | "onFocus"

// Discriminated unions — the pattern you should use everywhere
type Result<T> =
  | { success: true; data: T }
  | { success: false; error: string };
Enter fullscreen mode Exit fullscreen mode

Modern JavaScript — Patterns You Should Know

// Structured clone (deep copy without libraries)
const copy = structuredClone(originalObject);

// Object.groupBy (ES2024)
const grouped = Object.groupBy(users, (user) => user.role);
// { admin: [...], editor: [...], viewer: [...] }

// Array.fromAsync (ES2024)
const results = await Array.fromAsync(asyncIterable);

// Promise.withResolvers (ES2024)
const { promise, resolve, reject } = Promise.withResolvers();

// Optional chaining + nullish coalescing
const city = user?.address?.city ?? "Unknown";

// Logical assignment operators
options.timeout ??= 3000;       // assign if null/undefined
options.retries ||= 3;          // assign if falsy
options.verbose &&= isDebug();  // assign if truthy

// Using with AbortController for cancellable fetch
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
const response = await fetch(url, { signal: controller.signal });

// Pipeline-style array processing
const result = users
  .filter((u) => u.active)
  .map((u) => ({ name: u.name, score: u.points * u.multiplier }))
  .sort((a, b) => b.score - a.score)
  .slice(0, 10);
Enter fullscreen mode Exit fullscreen mode

Async Patterns — Beyond Basic Await

// Parallel execution (all must succeed)
const [users, posts, comments] = await Promise.all([
  fetchUsers(),
  fetchPosts(),
  fetchComments(),
]);

// Parallel execution (get all results, even failures)
const results = await Promise.allSettled([
  fetchUsers(),
  fetchPosts(),
  fetchComments(),
]);
results.forEach((r) => {
  if (r.status === "fulfilled") console.log(r.value);
  if (r.status === "rejected") console.error(r.reason);
});

// Race — first to resolve wins
const data = await Promise.race([
  fetchFromPrimary(),
  fetchFromFallback(),
]);

// Retry with exponential backoff
async function withRetry<T>(
  fn: () => Promise<T>,
  maxRetries = 3,
  baseDelay = 1000
): Promise<T> {
  for (let i = 0; i <= maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === maxRetries) throw error;
      await new Promise((r) => setTimeout(r, baseDelay * 2 ** i));
    }
  }
  throw new Error("Unreachable");
}
Enter fullscreen mode Exit fullscreen mode

Quick Reference Table

Feature JavaScript TypeScript Since
Optional chaining obj?.prop obj?.prop ES2020
Nullish coalescing a ?? b a ?? b ES2020
Logical assignment a ??= b a ??= b ES2021
structuredClone() Deep copy Deep copy ES2022
Top-level await In modules In modules ES2022
Array.findLast() From end From end ES2023
Object.groupBy() Group items Group items ES2024
Promise.withResolvers() Deferred Deferred ES2024
Map.groupBy() Map-based grouping Map-based grouping ES2024
Decorators Stage 3 experimentalDecorators ES2024+

Comparison: Module Systems

Feature ESM (import/export) CommonJS (require)
Syntax import x from 'y' const x = require('y')
Loading Static (analyzable) Dynamic (runtime)
Tree Shaking Yes No
Top-level Await Yes No
File Extension .mjs or "type": "module" .cjs or default
Browser Support Native Requires bundler
Circular Deps Live bindings (works) Partial object (fragile)
Default Export export default module.exports =

Usage Tips

  1. Start with the TypeScript utility types page — mastering Pick, Omit, Partial, and Record eliminates 80% of "how do I type this?" questions.
  2. Use the async patterns sheet next to your editor — the retry, race, and cancellation patterns come up in every project.
  3. Copy utility snippets directly — each one is tested, typed, and ready to paste into your codebase.
  4. Check the "Since" column in the reference table before using newer features — verify your target runtime supports them.
  5. Print the DOM API page for frontend work — it replaces jQuery-era habits with modern vanilla JS equivalents.

This is 1 of 11 resources in the Cheatsheet Reference Pro toolkit. Get the complete [JavaScript & TypeScript Reference] with all files, templates, and documentation for $15.

Get the Full Kit →

Or grab the entire Cheatsheet Reference Pro bundle (11 products) for $79 — save 30%.

Get the Complete Bundle →


Related Articles

Top comments (0)