[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7487T50P55CSXMWXZ0G9KRG":3,"skill-same:01M7487T50P55CSXMWXZ0G9KRG":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":29,"repositoryHtmlUrl":30,"repositoryHomepageUrl":6,"ownerHtmlUrl":31,"ownerBlogUrl":6,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M7487T50P55CSXMWXZ0G9KRG","typescript-patterns",null,"TypeScript patterns for strict, type-safe, maintainable code in modern TypeScript and JavaScript applications. Covers strict compiler configuration, type design, narrowing, discriminated unions, generics, async and error handling, module boundaries, dependency hygiene, and type-level testing. Use when writing or reviewing TypeScript or JavaScript code.","mdnaimul22\u002Fhuman-skills","mdnaimul22","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F64520358?v=4","01M70FH95MH2H796Q01TYSFZ03","Naimul","01M70FH96798CQR4YHA13F17GA",3,"MIT","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Ftypescript-patterns\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: typescript-patterns\ndescription: TypeScript patterns for strict, type-safe, maintainable code in modern TypeScript and JavaScript applications. Covers strict compiler configuration, type design, narrowing, discriminated unions, generics, async and error handling, module boundaries, dependency hygiene, and type-level testing. Use when writing or reviewing TypeScript or JavaScript code.\nmetadata:\n  origin: ECC\n---\n\n# TypeScript Development Patterns\n\nTypeScript patterns and best practices for building robust, type-safe, and maintainable applications. The compiler is most useful when it can prove your program's shape, so the guiding principle here is: push the type system to do real work instead of fighting it. This skill is the \"how.\" For the \"what\" and \"when\" (the decisions about which pattern to reach for), see the TypeScript rules — `rules\u002Ftypescript\u002Fcoding-style.md` and `rules\u002Ftypescript\u002Fpatterns.md` in this repository, installed as `rules\u002Fecc\u002Ftypescript\u002Fcoding-style.md` and `rules\u002Fecc\u002Ftypescript\u002Fpatterns.md`.\n\n## When to Activate\n\n- Writing new TypeScript or JavaScript code\n- Reviewing a PR that touches `.ts` or `.tsx` files\n- Refactoring existing TypeScript to remove `any`, tighten types, or add strictness\n- Designing types, generics, or module boundaries for a new feature\n- Setting up a new TypeScript project or upgrading `tsconfig.json`\n- Debugging type errors that cascade through a codebase (usually a design problem, not an annotation problem)\n\n## Core Principles\n\n### 1. Strict Mode Is the Baseline\n\n`strict: true` (which enables `strictNullChecks`, `noImplicitAny`, `strictFunctionTypes`, and the rest) is not optional in a healthy codebase. If a codebase cannot compile under strict, that is a migration task, not an excuse to leave the flag off.\n\n```jsonc\n\u002F\u002F tsconfig.json — a strict, discriminating baseline\n{\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"noUncheckedIndexedAccess\": true,\n    \"exactOptionalPropertyTypes\": true,\n    \"noImplicitOverride\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"noPropertyAccessFromIndexSignature\": true,\n    \"noUnusedLocals\": true,\n    \"noUnusedParameters\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"verbatimModuleSyntax\": true\n  }\n}\n```\n\n`noUncheckedIndexedAccess` makes array and record access possibly-undefined, which surfaces a whole class of runtime crashes at compile time. If it produces too much noise, this is the pattern to add, not the flag to remove:\n\n```typescript\n\u002F\u002F If you have proven the index exists, lift the element into a local first.\nconst [first] = items\nif (first === undefined) {\n  throw new Error(\"expected at least one item\")\n}\n```\n\n### 2. `any` Is a Bug, Not a Tool\n\n`any` disables the type system exactly where a bug is most likely to hide: at the boundary with untrusted or dynamic data. Prefer `unknown` and narrow it. When you truly need a fallback, prefer an explicit loosening with a comment over a silent `any`.\n\n```typescript\n\u002F\u002F Bad: any disables checking on the public API\nexport function parseConfig(raw: any): Config {\n  return raw.config ?? {}\n}\n\ninterface Config {\n  timeout: number\n  retries: number\n}\n\nconst DEFAULT_CONFIG: Config = { timeout: 30_000, retries: 3 }\n\nfunction isRecord(value: unknown): value is Record\u003Cstring, unknown> {\n  return typeof value === 'object' && value !== null\n}\n\nfunction toPositiveInt(value: unknown, field: string): number {\n  if (typeof value !== 'number' || !Number.isInteger(value) || value \u003C= 0) {\n    throw new TypeError(`Expected ${field} to be a positive integer`)\n  }\n  return value\n}\n\n\u002F\u002F Good: unknown forces safe narrowing at the edge. Every consumed field is\n\u002F\u002F validated with an explicit range, and defaults are declared up front.\nexport function parseConfig(raw: unknown): Config {\n  if (!isRecord(raw)) return { ...DEFAULT_CONFIG }\n  return {\n    timeout: raw['timeout'] === undefined ? DEFAULT_CONFIG.timeout : toPositiveInt(raw['timeout'], 'timeout'),\n    retries: raw['retries'] === undefined ? DEFAULT_CONFIG.retries : toPositiveInt(raw['retries'], 'retries'),\n  }\n}\n```\n\n### 3. Public APIs Get Explicit Types, Locals Get Inference\n\nTypeScript infers local variables well. Exporting functions whose parameter and return types are implicit leaks inference decisions into every consumer and makes intent unreadable.\n\n```typescript\n\u002F\u002F Bad: exported API without explicit types\nexport function formatUser(user) {\n  return `${user.firstName} ${user.lastName}`\n}\n\n\u002F\u002F Good: explicit public contract, inferred internals\ninterface User {\n  firstName: string\n  lastName: string\n}\n\nexport function formatUser(user: User): string {\n  return `${user.firstName} ${user.lastName}`\n}\n```\n\n## Type Design\n\n### Interfaces vs. Type Aliases\n\n`interface` for object shapes that may be extended or implemented; `type` for unions, intersections, tuples, mapped types, and utility types. Prefer string-literal unions over `enum` unless you need runtime value enumeration or interop with code that requires it.\n\n```typescript\ninterface User {\n  id: string\n  email: string\n}\n\ntype UserRole = 'admin' | 'member'\ntype AdminUser = User & { role: 'admin' }\n```\n\n### Discriminated Unions Are the Default State Machine\n\nWhen a value can be in multiple shapes, model it as a discriminated union with a literal `type`\u002F`kind` field. Exhaustive checking then becomes a free compiler feature: never a runtime fallback, always a compile error on a missing branch.\n\n```typescript\ntype Transaction =\n  | { kind: 'draft'; id: string }\n  | { kind: 'submitted'; id: string; submittedAt: Date }\n  | { kind: 'paid'; id: string; paidAt: Date; amountCents: number }\n\nfunction describe(t: Transaction): string {\n  switch (t.kind) {\n    case 'draft':\n      return 'Saved but not sent'\n    case 'submitted':\n      return `Submitted on ${t.submittedAt.toISOString()}`\n    case 'paid':\n      return `Paid ${t.amountCents} cents on ${t.paidAt.toISOString()}`\n    default:\n      \u002F\u002F exhaustive: any new member forces this to fail to compile\n      return assertNever(t)\n  }\n}\n\nfunction assertNever(value: never): never {\n  throw new Error(`Unhandled member: ${JSON.stringify(value)}`)\n}\n```\n\n### Brands and Nominal Safety Where Structure Is Not Enough\n\nStructural typing cannot tell `CustomerId` from `string`. When an ID or unit must not be confused with another, add a brand (a phantom field with a unique symbol key).\n\n```typescript\ndeclare const brand: unique symbol\n\nexport type CustomerId = string & { [brand]: 'CustomerId' }\n\nfunction ensureCustomerId(value: string): CustomerId {\n  if (!\u002F^cus_[a-z0-9]+$\u002F.test(value)) {\n    throw new TypeError(`Invalid customer id: ${value}`)\n  }\n  return value as CustomerId\n}\n```\n\nKeep brands internal to a boundary module; never expose the cast helper far from the validation that justifies it.\n\n### Generics Model Caller-Dependent Types\n\nIf a value's type depends on what the caller supplies, make it generic rather than flattening to `any` or `unknown` and hand-casting at call sites.\n\n```typescript\n\u002F\u002F Bad: caller must cast the result\nexport function getCached(key: string): unknown {\n  return cache.get(key)\n}\n\n\u002F\u002F Good: the caller's type flows through\nexport function getCached\u003CT>(key: string, parse: (raw: string) => T): T | undefined {\n  const raw = cache.get(key)\n  if (raw === undefined) return undefined\n  return parse(raw)\n}\n```\n\nConstrain generics so the contract is discoverable: prefer `T extends SomeShape` over free-floating `T` when a shape assumption exists.\n\n### Options Objects over Positional Parameters\n\nFunctions with more than a couple of knobs should take a single options object. It makes call sites self-documenting and lets new knobs be added without positional churn.\n\n```typescript\ninterface FetchOptions {\n  timeoutMs?: number\n  retries?: number\n  signal?: AbortSignal\n}\n\nexport async function fetchWithRetry(url: string, options: FetchOptions = {}): Promise\u003CResponse> {\n  \u002F\u002F ...\n}\n```\n\n## Narrowing and Runtime Safety\n\n### Validate at the Boundary, Trust Inside\n\nUntrusted data enters at I\u002FO boundaries: API handlers, message consumers, file loaders. Parse and validate once with a schema, then carry the refined type through the domain. This is where a validation library (for example, Zod) earns its keep — the schema is both the runtime check and the compile-time type.\n\n```typescript\nimport { z } from 'zod'\n\nconst userInputSchema = z.object({\n  email: z.string().email(),\n  age: z.number().int().min(0).max(150)\n})\n\nexport type UserInput = z.infer\u003Ctypeof userInputSchema>\n\n\u002F\u002F validate once at the edge\nconst input: UserInput = userInputSchema.parse(rawBody)\n```\n\n### Type Predicates and Assertion Functions\n\nPrefer type predicates and assertion functions over unchecked casts when guarding shapes. The guard documents the invariant and the compiler checks its usage.\n\n```typescript\nfunction isConfig(value: unknown): value is Config {\n  if (typeof value !== 'object' || value === null) return false\n  if (!('timeout' in value) || !('retries' in value)) return false\n  const { timeout, retries } = value\n  return (\n    typeof timeout === 'number' && Number.isInteger(timeout) && timeout > 0 &&\n    typeof retries === 'number' && Number.isInteger(retries) && retries > 0\n  )\n}\n```\n\nTo fail loudly on a malformed value instead of returning a boolean, use an assertion signature:\n\n```typescript\nfunction assertIsStringArray(value: unknown): asserts value is string[] {\n  if (!Array.isArray(value)) {\n    throw new TypeError('Expected an array of strings')\n  }\n  \u002F\u002F Iteration visits sparse positions as undefined instead of skipping them.\n  for (const item of value) {\n    if (typeof item !== 'string') throw new TypeError('Expected an array of strings')\n  }\n}\n```\n\n### Readonly by Default\n\nMark array and object parameters `readonly`\u002F`ReadonlyArray` when the function does not mutate them. It prevents accidental mutation and signals intent at the signature. (Per the coding-style rules, prefer the spread operator for immutable updates.)\n\n```typescript\nexport function totalAmount(items: readonly LineItem[]): number {\n  return items.reduce((sum, item) => sum + item.amountCents, 0)\n}\n```\n\nRuntime immutability (for example, `Object.freeze`) is for hot application boundaries; `readonly` in type positions is the everyday guard.\n\n## Error Handling\n\n### Fail at the Boundary, Handle at the Edge\n\nThe `try\u002Fcatch` belongs where the caller can act on failure — not wrapped around every internal call in a stack of swallowed errors. Use async\u002Fawait with `try\u002Fcatch` and narrow `unknown` errors safely (per the coding-style rules).\n\nThis endpoint example accepts non-empty IDs made of ASCII letters, digits, underscores, and hyphens, such as `u_1`. Validate that contract before constructing the path or making a request. Adapt the identifier grammar to the real API.\n\n```typescript\ntype User = { id: string; email: string }\n\nfunction isUser(value: unknown): value is User {\n  if (typeof value !== 'object' || value === null) return false\n  if (!('id' in value) || !('email' in value)) return false\n  const { id, email } = value\n  return (\n    typeof id === 'string' && id.length > 0 &&\n    typeof email === 'string' && email.includes('@')\n  )\n}\n\nfunction assertUserId(userId: string): void {\n  if (typeof userId !== 'string' || userId.length === 0 || \u002F[^A-Za-z0-9_-]\u002F.test(userId)) {\n    throw new TypeError('Expected a user ID using letters, digits, \"_\" or \"-\"')\n  }\n}\n\nasync function loadUser(userId: string): Promise\u003CUser> {\n  assertUserId(userId)\n  const response = await fetch(`\u002Fusers\u002F${userId}`)\n  if (!response.ok) {\n    throw new Error(`Failed to load user ${userId}: ${response.status}`)\n  }\n  const data: unknown = await response.json()\n  if (!isUser(data)) {\n    throw new TypeError(`Invalid user payload for ${userId}`)\n  }\n  return data\n}\n\nexport async function getUser(userId: string): Promise\u003CUser> {\n  try {\n    return await loadUser(userId)\n  } catch (error: unknown) {\n    if (error instanceof Error) {\n      \u002F\u002F known failure mode: retry or surface a friendly message\n      throw new Error(`user lookup failed: ${error.message}`, { cause: error })\n    }\n    throw new TypeError('unknown error shape')\n  }\n}\n```\n\n### Result Types for Expected Failures\n\nFor expected business failures (validation, not-found, conflict), a discriminated `Result` union makes failure explicit in the type instead of hiding it in the exception flow.\n\n```typescript\ntype Result\u003CT, E> = { ok: true; value: T } | { ok: false; error: E }\n\nfunction createUser(input: UserInput): Result\u003CUser, ValidationIssue[]> {\n  const issues = validate(input)\n  if (issues.length > 0) {\n    return { ok: false, error: issues }\n  }\n  return { ok: true, value: { id: generateId(), ...input } }\n}\n```\n\nReserve exceptions for the unexpected. Expected outcomes belong in the return type.\n\n### Preserve Error Context\n\nUse `new Error(message, { cause })` (available since ES2022) so the original failure chain survives rewrapping. Never stringify errors into a message and lose the cause.\n\n## Async Patterns\n\n### Prefer `Promise.allSettled` for Independent Fan-Out\n\nWhen results are independent and one failure must not drop the others, use `Promise.allSettled` and handle the per-promise outcomes.\n\n```typescript\nconst results: PromiseSettledResult\u003Cnumber>[] = await Promise.allSettled(\n  sourceIds.map((id) => fetchCount(id))\n)\n\nconst total = results.reduce((sum, result) => {\n  if (result.status === 'fulfilled') {\n    return sum + result.value\n  }\n  log.warn('count fetch failed', result.reason)\n  return sum\n}, 0)\n```\n\nUse `Promise.all` when you want fail-fast semantics — genuinely all-or-nothing work.\n\n### Avoid Unbounded Concurrency\n\nFanning out hundreds of promises at once overwhelms connections and event loop. Bound the concurrency with a small pool.\n\n```typescript\nasync function mapWithConcurrency\u003CT, R>(\n  items: readonly T[],\n  limit: number,\n  mapper: (item: T) => Promise\u003CR>\n): Promise\u003CR[]> {\n  if (!Number.isInteger(limit) || limit \u003C 1) {\n    throw new RangeError(`Expected concurrency limit to be a positive integer, got: ${limit}`)\n  }\n  const results: R[] = new Array(items.length)\n  let nextIndex = 0\n\n  const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {\n    while (true) {\n      const index = nextIndex++\n      if (index >= items.length) return\n      \u002F\u002F Required under noUncheckedIndexedAccess: the index is proven\n      \u002F\u002F in-bounds above, but the compiler still types this T | undefined.\n      \u002F\u002F Skip only genuine sparse-array holes, mirroring Array.prototype.map:\n      \u002F\u002F a present `undefined` element is a legitimate value and must still\n      \u002F\u002F reach the mapper.\n      if (!Object.hasOwn(items, index)) continue\n      \u002F\u002F Presence is proven above, so the indexed access is in-bounds and\n      \u002F\u002F filled — never a hole and never the compiler's speculative undefined.\n      results[index] = await mapper(items[index]!)\n    }\n  })\n\n  \u002F\u002F One worker rejecting rejects the whole pool: Promise.all propagates the\n  \u002F\u002F first rejection to the caller (fail-fast). That is rejection, not\n  \u002F\u002F cancellation — the other workers keep running and may settle more of\n  \u002F\u002F their remaining items after the pool has already rejected. Use\n  \u002F\u002F Promise.all only when leaving that in-flight work running is acceptable;\n  \u002F\u002F otherwise use allSettled or thread an AbortSignal through the mapper.\n  await Promise.all(workers)\n  return results\n}\n```\n\n### Timeouts and Cancellation\n\nAlways thread `AbortSignal` through long-running or outbound work so callers can cancel; pair it with `Promise.race` for hard timeouts where the underlying operation cannot be aborted.\n\n```typescript\nfunction withTimeout\u003CT>(promise: Promise\u003CT>, ms: number): Promise\u003CT> {\n  return new Promise((resolve, reject) => {\n    const timer = setTimeout(() => reject(new Error(`Timed out after ${ms}ms`)), ms)\n    promise.then(\n      (value) => {\n        clearTimeout(timer)\n        resolve(value)\n      },\n      (reason) => {\n        clearTimeout(timer)\n        reject(reason)\n      }\n    )\n  })\n}\n```\n\n## Null and Undefined Discipline\n\nPrefer a discriminated approach over mixing sentinel values. Where \"not found\" or \"absent\" is a legitimate state, use `T | undefined` and check explicitly; avoid deeply nesting `?.` chains followed by silent fallbacks that hide bugs.\n\n```typescript\nfunction findUser(id: string): User | undefined {\n  return users.get(id)\n}\n\nconst user = findUser('u_1')\nif (user === undefined) {\n  return notFound()\n}\n\u002F\u002F from here on, `user` is narrowed to User\n```\n\nAvoid truthiness checks that silently accept wrong types (`if (result)` when `result` may be `0` or `''`). Compare against `undefined`\u002F`null` explicitly.\n\n## Module Boundaries and Exports\n\n### Small, Named Modules\n\nExpose a deliberate surface at each module's boundary. Prefer explicit named exports over default exports, and re-export at the public edge so consumers import from the module that owns the type — not from deep internals that can be refactored.\n\n```typescript\n\u002F\u002F user\u002Fmodel.ts — internal types\nexport interface UserAccount {\n  id: string\n  email: string\n  role: UserRole\n}\n\n\u002F\u002F user\u002Findex.ts — public surface\nexport { type UserAccount, type UserRole } from '.\u002Fmodel'\nexport { createUser, findUser, updateUser } from '.\u002Fservice'\n```\n\n### Avoid Barrel Bloat and Circular Imports\n\nDo not create barrels that import everything at module load (they defeat tree-shaking and grow cold-start). Import concrete paths. Circular imports signal a submission boundary that should fold upward; the type that both sides need belongs in a shared module neither imports.\n\n### Split by Dependency Direction\n\nLet the type graph point the way: types that cross boundaries go in a contract module; implementations import the contract; nothing imports implementations from contracts. In a node\u002Fbackend codebase that means roughly: `domain` (pure types and rules) → `application` (use cases) → `infrastructure` (adapters), with dependencies pointing only inward.\n\n## Dependencies and Build\n\n### Diagnose, Then Add Dependencies\n\nPrefer built-in `Array`, `Map`, `Promise`, and `Intl` over pulling in utilities for every small operation. A tiny inline function beats a dependency that must be upgraded, audited, and kept compatible. (The Go idiom \"a little copying is better than a little dependency\" applies to TypeScript too.)\n\n### Runtime Validation, Not Type-of-Trust\n\nSchemas that validate at runtime (Zod, validators, or hand-written guards) are the bridge between untrusted data and compile-time types. Library approaches differ (Zod and other schema-first libraries derive the type from the schema; validators in some ecosystem patterns are type-first with the runtime check derived). Pick one model and be consistent across the codebase.\n\n### Keep the Compiler Incremental and Fast\n\nLarge codebases benefit from `composite: true` with project references, an `incremental` build cache, and `moduleResolution: bundler` where the bundler supports it. Slow type-checking is a workflow problem that pushes developers off the type system — invest in narrowing the checked surface over relaxing it.\n\n## Performance\n\n### Types Are Free, Structures Are Not\n\nType-level gymnastics (mapped types, conditional types, template literal types) cost nothing at runtime but can cost a lot of developer clarity. Keep complex type machinery inside boundary modules; do not export type circus acts as the public API.\n\n### Avoid Unnecessary Object Renaming\n\nCopying and spreading large nested objects repeatedly has real cost in hot paths. Prefer immutable updates with spread at the point of change, but avoid defensive re-copying of unchanged structures (for example, in render paths or per-message handlers).\n\n### Memoize Idempotent Computation\n\nPure, expensive derivations belong behind a cache if they repeat with the same inputs. Use `Map`-based caches with explicit lifetime instead of ad-hoc global caches that never clear.\n\n## Type-Level Testing\n\n### Assert the Types, Not Just the Runtime\n\nBehavior tests prove runtime behavior; dedicated type tests lock in the public API contract. A type that silently loosens is a regression.\n\n```typescript\nimport { expectTypeOf } from 'vitest'\n\nexpectTypeOf\u003CResult\u003CUser, ValidationIssue[]>>().toEqualTypeOf\u003C\n  | { ok: true; value: User }\n  | { ok: false; error: ValidationIssue[] }\n>()\n```\n\n### Use `satisfies` to Preserve Intent\n\n`satisfies` checks a value against a shape without widening it to that shape — the ideal way to keep literal types while still validating structure.\n\n```typescript\nconst statusByAction = {\n  new: 'open',\n  reopen: 'open',\n  close: 'closed'\n} as const satisfies Record\u003CAction, Status>\n```\n\n## TypeScript Tooling Integration\n\n### Essential Commands\n\n```bash\n# Type-check the whole project\nnpx tsc --noEmit\n\n# Watch mode for fast feedback\nnpx tsc --noEmit --watch\n\n# Run tests (Vitest)\nnpx vitest run\n\n# Lint with types-aware rules (typescript-eslint)\nnpx eslint .\n\n# Formatting\nnpx prettier --write .\n```\n\n### Recommended Linter Baseline\n\nThe `typescript-eslint` recommended-type-checked ruleset is the practical default: it promotes `no-unsafe-assignment`, `no-unsafe-member-access`, `no-unsafe-argument`, and `no-unsafe-call` from style noise to compiler-like guarantees. Keep the type-aware config; if it is slow, that is a project-structure signal, not a reason to disable it.\n\n## Anti-Patterns to Avoid\n\n- **`any` as a speed hack** — it converts the compiler's proof into a runtime guess. Reach for `unknown` + narrowing instead.\n- **`as` casts that lie** — a cast that bypasses a check you did not actually perform is where null-pointer and shape bugs are born. Validate, then cast, and keep the cast inside the module that validates.\n- **Deeply nested callbacks \u002F promise chains** — prefer async\u002Fawait; flat code is narrowable code.\n- **`enum` coercion bugs** — string-literal unions give you the same safety without runtime artifacts or reverse-mapping footguns.\n- **Giant god types** — a single interface that models several unrelated shapes should be a discriminated union or several interfaces.\n- **Optional-only option objects** — `allOptional` config types silently swallow typos at the call site; prefer required fields for the ones the function genuinely depends on.\n- **Silent catch** — `catch {}` or `catch (e) { \u002F* nothing *\u002F }` hides failures the caller assumed were handled.\n- **Mixing sync and async error paths** — an `async` function always surfaces throws as rejections, even before the first `await`. Only a non-`async` function returning a promise can throw synchronously (before returning it), forcing callers to handle two error shapes. Prefer `async` throughout so every failure is a rejection:\n\n```typescript\nasync function asyncFails(): Promise\u003Cnever> {\n  throw new Error('becomes a rejection, never a sync throw')\n}\n\nfunction lazyFails(): Promise\u003Cnever> {\n  throw new Error('throws synchronously — needs try\u002Fcatch AND .catch')\n}\n```\n\n**Remember**: the type system is a proof tool, not a paperwork burden. When a type error resists a reasonable annotation, the design — not the compiler — is usually the thing to change. Prefer boring, explicit, well-scoped TypeScript over clever type engines.\n\n## Related Skills\n\n- `nestjs-patterns` — NestJS architecture patterns for TypeScript backends (modules, controllers, providers, DTO validation)\n- `frontend-patterns` — React and Next.js component and state patterns\n- TypeScript rules (`rules\u002Ftypescript\u002F`, installed as `rules\u002Fecc\u002Ftypescript\u002F`) — the \"what\" and \"when\" this skill implements as the \"how\"\n- `prisma-patterns` — database access patterns used in TypeScript applications\n","# TypeScript Development Patterns\n\nTypeScript patterns and best practices for building robust, type-safe, and maintainable applications. The compiler is most useful when it can prove your program's shape, so the guiding principle here is: push the type system to do real work instead of fighting it. This skill is the \"how.\" For the \"what\" and \"when\" (the decisions about which pattern to reach for), see the TypeScript rules — `rules\u002Ftypescript\u002Fcoding-style.md` and `rules\u002Ftypescript\u002Fpatterns.md` in this repository, installed as `rules\u002Fecc\u002Ftypescript\u002Fcoding-style.md` and `rules\u002Fecc\u002Ftypescript\u002Fpatterns.md`.\n\n## When to Activate\n\n- Writing new TypeScript or JavaScript code\n- Reviewing a PR that touches `.ts` or `.tsx` files\n- Refactoring existing TypeScript to remove `any`, tighten types, or add strictness\n- Designing types, generics, or module boundaries for a new feature\n- Setting up a new TypeScript project or upgrading `tsconfig.json`\n- Debugging type errors that cascade through a codebase (usually a design problem, not an annotation problem)\n\n## Core Principles\n\n### 1. Strict Mode Is the Baseline\n\n`strict: true` (which enables `strictNullChecks`, `noImplicitAny`, `strictFunctionTypes`, and the rest) is not optional in a healthy codebase. If a codebase cannot compile under strict, that is a migration task, not an excuse to leave the flag off.\n\n```jsonc\n\u002F\u002F tsconfig.json — a strict, discriminating baseline\n{\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"noUncheckedIndexedAccess\": true,\n    \"exactOptionalPropertyTypes\": true,\n    \"noImplicitOverride\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"noPropertyAccessFromIndexSignature\": true,\n    \"noUnusedLocals\": true,\n    \"noUnusedParameters\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"verbatimModuleSyntax\": true\n  }\n}\n```\n\n`noUncheckedIndexedAccess` makes array and record access possibly-undefined, which surfaces a whole class of runtime crashes at compile time. If it produces too much noise, this is the pattern to add, not the flag to remove:\n\n```typescript\n\u002F\u002F If you have proven the index exists, lift the element into a local first.\nconst [first] = items\nif (first === undefined) {\n  throw new Error(\"expected at least one item\")\n}\n```\n\n### 2. `any` Is a Bug, Not a Tool\n\n`any` disables the type system exactly where a bug is most likely to hide: at the boundary with untrusted or dynamic data. Prefer `unknown` and narrow it. When you truly need a fallback, prefer an explicit loosening with a comment over a silent `any`.\n\n```typescript\n\u002F\u002F Bad: any disables checking on the public API\nexport function parseConfig(raw: any): Config {\n  return raw.config ?? {}\n}\n\ninterface Config {\n  timeout: number\n  retries: number\n}\n\nconst DEFAULT_CONFIG: Config = { timeout: 30_000, retries: 3 }\n\nfunction isRecord(value: unknown): value is Record\u003Cstring, unknown> {\n  return typeof value === 'object' && value !== null\n}\n\nfunction toPositiveInt(value: unknown, field: string): number {\n  if (typeof value !== 'number' || !Number.isInteger(value) || value \u003C= 0) {\n    throw new TypeError(`Expected ${field} to be a positive integer`)\n  }\n  return value\n}\n\n\u002F\u002F Good: unknown forces safe narrowing at the edge. Every consumed field is\n\u002F\u002F validated with an explicit range, and defaults are declared up front.\nexport function parseConfig(raw: unknown): Config {\n  if (!isRecord(raw)) return { ...DEFAULT_CONFIG }\n  return {\n    timeout: raw['timeout'] === undefined ? DEFAULT_CONFIG.timeout : toPositiveInt(raw['timeout'], 'timeout'),\n    retries: raw['retries'] === undefined ? DEFAULT_CONFIG.retries : toPositiveInt(raw['retries'], 'retries'),\n  }\n}\n```\n\n### 3. Public APIs Get Explicit Types, Locals Get Inference\n\nTypeScript infers local variables well. Exporting functions whose parameter and return types are implicit leaks inference decisions into every consumer and makes intent unreadable.\n\n```typescript\n\u002F\u002F Bad: exported API without explicit types\nexport function formatUser(user) {\n  return `${user.firstName} ${user.lastName}`\n}\n\n\u002F\u002F Good: explicit public contract, inferred internals\ninterface User {\n  firstName: string\n  lastName: string\n}\n\nexport function formatUser(user: User): string {\n  return `${user.firstName} ${user.lastName}`\n}\n```\n\n## Type Design\n\n### Interfaces vs. Type Aliases\n\n`interface` for object shapes that may be extended or implemented; `type` for unions, intersections, tuples, mapped types, and utility types. Prefer string-literal unions over `enum` unless you need runtime value enumeration or interop with code that requires it.\n\n```typescript\ninterface User {\n  id: string\n  email: string\n}\n\ntype UserRole = 'admin' | 'member'\ntype AdminUser = User & { role: 'admin' }\n```\n\n### Discriminated Unions Are the Default State Machine\n\nWhen a value can be in multiple shapes, model it as a discriminated union with a literal `type`\u002F`kind` field. Exhaustive checking then becomes a free compiler feature: never a runtime fallback, always a compile error on a missing branch.\n\n```typescript\ntype Transaction =\n  | { kind: 'draft'; id: string }\n  | { kind: 'submitted'; id: string; submittedAt: Date }\n  | { kind: 'paid'; id: string; paidAt: Date; amountCents: number }\n\nfunction describe(t: Transaction): string {\n  switch (t.kind) {\n    case 'draft':\n      return 'Saved but not sent'\n    case 'submitted':\n      return `Submitted on ${t.submittedAt.toISOString()}`\n    case 'paid':\n      return `Paid ${t.amountCents} cents on ${t.paidAt.toISOString()}`\n    default:\n      \u002F\u002F exhaustive: any new member forces this to fail to compile\n      return assertNever(t)\n  }\n}\n\nfunction assertNever(value: never): never {\n  throw new Error(`Unhandled member: ${JSON.stringify(value)}`)\n}\n```\n\n### Brands and Nominal Safety Where Structure Is Not Enough\n\nStructural typing cannot tell `CustomerId` from `string`. When an ID or unit must not be confused with another, add a brand (a phantom field with a unique symbol key).\n\n```typescript\ndeclare const brand: unique symbol\n\nexport type CustomerId = string & { [brand]: 'CustomerId' }\n\nfunction ensureCustomerId(value: string): CustomerId {\n  if (!\u002F^cus_[a-z0-9]+$\u002F.test(value)) {\n    throw new TypeError(`Invalid customer id: ${value}`)\n  }\n  return value as CustomerId\n}\n```\n\nKeep brands internal to a boundary module; never expose the cast helper far from the validation that justifies it.\n\n### Generics Model Caller-Dependent Types\n\nIf a value's type depends on what the caller supplies, make it generic rather than flattening to `any` or `unknown` and hand-casting at call sites.\n\n```typescript\n\u002F\u002F Bad: caller must cast the result\nexport function getCached(key: string): unknown {\n  return cache.get(key)\n}\n\n\u002F\u002F Good: the caller's type flows through\nexport function getCached\u003CT>(key: string, parse: (raw: string) => T): T | undefined {\n  const raw = cache.get(key)\n  if (raw === undefined) return undefined\n  return parse(raw)\n}\n```\n\nConstrain generics so the contract is discoverable: prefer `T extends SomeShape` over free-floating `T` when a shape assumption exists.\n\n### Options Objects over Positional Parameters\n\nFunctions with more than a couple of knobs should take a single options object. It makes call sites self-documenting and lets new knobs be added without positional churn.\n\n```typescript\ninterface FetchOptions {\n  timeoutMs?: number\n  retries?: number\n  signal?: AbortSignal\n}\n\nexport async function fetchWithRetry(url: string, options: FetchOptions = {}): Promise\u003CResponse> {\n  \u002F\u002F ...\n}\n```\n\n## Narrowing and Runtime Safety\n\n### Validate at the Boundary, Trust Inside\n\nUntrusted data enters at I\u002FO boundaries: API handlers, message consumers, file loaders. Parse and validate once with a schema, then carry the refined type through the domain. This is where a validation library (for example, Zod) earns its keep — the schema is both the runtime check and the compile-time type.\n\n```typescript\nimport { z } from 'zod'\n\nconst userInputSchema = z.object({\n  email: z.string().email(),\n  age: z.number().int().min(0).max(150)\n})\n\nexport type UserInput = z.infer\u003Ctypeof userInputSchema>\n\n\u002F\u002F validate once at the edge\nconst input: UserInput = userInputSchema.parse(rawBody)\n```\n\n### Type Predicates and Assertion Functions\n\nPrefer type predicates and assertion functions over unchecked casts when guarding shapes. The guard documents the invariant and the compiler checks its usage.\n\n```typescript\nfunction isConfig(value: unknown): value is Config {\n  if (typeof value !== 'object' || value === null) return false\n  if (!('timeout' in value) || !('retries' in value)) return false\n  const { timeout, retries } = value\n  return (\n    typeof timeout === 'number' && Number.isInteger(timeout) && timeout > 0 &&\n    typeof retries === 'number' && Number.isInteger(retries) && retries > 0\n  )\n}\n```\n\nTo fail loudly on a malformed value instead of returning a boolean, use an assertion signature:\n\n```typescript\nfunction assertIsStringArray(value: unknown): asserts value is string[] {\n  if (!Array.isArray(value)) {\n    throw new TypeError('Expected an array of strings')\n  }\n  \u002F\u002F Iteration visits sparse positions as undefined instead of skipping them.\n  for (const item of value) {\n    if (typeof item !== 'string') throw new TypeError('Expected an array of strings')\n  }\n}\n```\n\n### Readonly by Default\n\nMark array and object parameters `readonly`\u002F`ReadonlyArray` when the function does not mutate them. It prevents accidental mutation and signals intent at the signature. (Per the coding-style rules, prefer the spread operator for immutable updates.)\n\n```typescript\nexport function totalAmount(items: readonly LineItem[]): number {\n  return items.reduce((sum, item) => sum + item.amountCents, 0)\n}\n```\n\nRuntime immutability (for example, `Object.freeze`) is for hot application boundaries; `readonly` in type positions is the everyday guard.\n\n## Error Handling\n\n### Fail at the Boundary, Handle at the Edge\n\nThe `try\u002Fcatch` belongs where the caller can act on failure — not wrapped around every internal call in a stack of swallowed errors. Use async\u002Fawait with `try\u002Fcatch` and narrow `unknown` errors safely (per the coding-style rules).\n\nThis endpoint example accepts non-empty IDs made of ASCII letters, digits, underscores, and hyphens, such as `u_1`. Validate that contract before constructing the path or making a request. Adapt the identifier grammar to the real API.\n\n```typescript\ntype User = { id: string; email: string }\n\nfunction isUser(value: unknown): value is User {\n  if (typeof value !== 'object' || value === null) return false\n  if (!('id' in value) || !('email' in value)) return false\n  const { id, email } = value\n  return (\n    typeof id === 'string' && id.length > 0 &&\n    typeof email === 'string' && email.includes('@')\n  )\n}\n\nfunction assertUserId(userId: string): void {\n  if (typeof userId !== 'string' || userId.length === 0 || \u002F[^A-Za-z0-9_-]\u002F.test(userId)) {\n    throw new TypeError('Expected a user ID using letters, digits, \"_\" or \"-\"')\n  }\n}\n\nasync function loadUser(userId: string): Promise\u003CUser> {\n  assertUserId(userId)\n  const response = await fetch(`\u002Fusers\u002F${userId}`)\n  if (!response.ok) {\n    throw new Error(`Failed to load user ${userId}: ${response.status}`)\n  }\n  const data: unknown = await response.json()\n  if (!isUser(data)) {\n    throw new TypeError(`Invalid user payload for ${userId}`)\n  }\n  return data\n}\n\nexport async function getUser(userId: string): Promise\u003CUser> {\n  try {\n    return await loadUser(userId)\n  } catch (error: unknown) {\n    if (error instanceof Error) {\n      \u002F\u002F known failure mode: retry or surface a friendly message\n      throw new Error(`user lookup failed: ${error.message}`, { cause: error })\n    }\n    throw new TypeError('unknown error shape')\n  }\n}\n```\n\n### Result Types for Expected Failures\n\nFor expected business failures (validation, not-found, conflict), a discriminated `Result` union makes failure explicit in the type instead of hiding it in the exception flow.\n\n```typescript\ntype Result\u003CT, E> = { ok: true; value: T } | { ok: false; error: E }\n\nfunction createUser(input: UserInput): Result\u003CUser, ValidationIssue[]> {\n  const issues = validate(input)\n  if (issues.length > 0) {\n    return { ok: false, error: issues }\n  }\n  return { ok: true, value: { id: generateId(), ...input } }\n}\n```\n\nReserve exceptions for the unexpected. Expected outcomes belong in the return type.\n\n### Preserve Error Context\n\nUse `new Error(message, { cause })` (available since ES2022) so the original failure chain survives rewrapping. Never stringify errors into a message and lose the cause.\n\n## Async Patterns\n\n### Prefer `Promise.allSettled` for Independent Fan-Out\n\nWhen results are independent and one failure must not drop the others, use `Promise.allSettled` and handle the per-promise outcomes.\n\n```typescript\nconst results: PromiseSettledResult\u003Cnumber>[] = await Promise.allSettled(\n  sourceIds.map((id) => fetchCount(id))\n)\n\nconst total = results.reduce((sum, result) => {\n  if (result.status === 'fulfilled') {\n    return sum + result.value\n  }\n  log.warn('count fetch failed', result.reason)\n  return sum\n}, 0)\n```\n\nUse `Promise.all` when you want fail-fast semantics — genuinely all-or-nothing work.\n\n### Avoid Unbounded Concurrency\n\nFanning out hundreds of promises at once overwhelms connections and event loop. Bound the concurrency with a small pool.\n\n```typescript\nasync function mapWithConcurrency\u003CT, R>(\n  items: readonly T[],\n  limit: number,\n  mapper: (item: T) => Promise\u003CR>\n): Promise\u003CR[]> {\n  if (!Number.isInteger(limit) || limit \u003C 1) {\n    throw new RangeError(`Expected concurrency limit to be a positive integer, got: ${limit}`)\n  }\n  const results: R[] = new Array(items.length)\n  let nextIndex = 0\n\n  const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {\n    while (true) {\n      const index = nextIndex++\n      if (index >= items.length) return\n      \u002F\u002F Required under noUncheckedIndexedAccess: the index is proven\n      \u002F\u002F in-bounds above, but the compiler still types this T | undefined.\n      \u002F\u002F Skip only genuine sparse-array holes, mirroring Array.prototype.map:\n      \u002F\u002F a present `undefined` element is a legitimate value and must still\n      \u002F\u002F reach the mapper.\n      if (!Object.hasOwn(items, index)) continue\n      \u002F\u002F Presence is proven above, so the indexed access is in-bounds and\n      \u002F\u002F filled — never a hole and never the compiler's speculative undefined.\n      results[index] = await mapper(items[index]!)\n    }\n  })\n\n  \u002F\u002F One worker rejecting rejects the whole pool: Promise.all propagates the\n  \u002F\u002F first rejection to the caller (fail-fast). That is rejection, not\n  \u002F\u002F cancellation — the other workers keep running and may settle more of\n  \u002F\u002F their remaining items after the pool has already rejected. Use\n  \u002F\u002F Promise.all only when leaving that in-flight work running is acceptable;\n  \u002F\u002F otherwise use allSettled or thread an AbortSignal through the mapper.\n  await Promise.all(workers)\n  return results\n}\n```\n\n### Timeouts and Cancellation\n\nAlways thread `AbortSignal` through long-running or outbound work so callers can cancel; pair it with `Promise.race` for hard timeouts where the underlying operation cannot be aborted.\n\n```typescript\nfunction withTimeout\u003CT>(promise: Promise\u003CT>, ms: number): Promise\u003CT> {\n  return new Promise((resolve, reject) => {\n    const timer = setTimeout(() => reject(new Error(`Timed out after ${ms}ms`)), ms)\n    promise.then(\n      (value) => {\n        clearTimeout(timer)\n        resolve(value)\n      },\n      (reason) => {\n        clearTimeout(timer)\n        reject(reason)\n      }\n    )\n  })\n}\n```\n\n## Null and Undefined Discipline\n\nPrefer a discriminated approach over mixing sentinel values. Where \"not found\" or \"absent\" is a legitimate state, use `T | undefined` and check explicitly; avoid deeply nesting `?.` chains followed by silent fallbacks that hide bugs.\n\n```typescript\nfunction findUser(id: string): User | undefined {\n  return users.get(id)\n}\n\nconst user = findUser('u_1')\nif (user === undefined) {\n  return notFound()\n}\n\u002F\u002F from here on, `user` is narrowed to User\n```\n\nAvoid truthiness checks that silently accept wrong types (`if (result)` when `result` may be `0` or `''`). Compare against `undefined`\u002F`null` explicitly.\n\n## Module Boundaries and Exports\n\n### Small, Named Modules\n\nExpose a deliberate surface at each module's boundary. Prefer explicit named exports over default exports, and re-export at the public edge so consumers import from the module that owns the type — not from deep internals that can be refactored.\n\n```typescript\n\u002F\u002F user\u002Fmodel.ts — internal types\nexport interface UserAccount {\n  id: string\n  email: string\n  role: UserRole\n}\n\n\u002F\u002F user\u002Findex.ts — public surface\nexport { type UserAccount, type UserRole } from '.\u002Fmodel'\nexport { createUser, findUser, updateUser } from '.\u002Fservice'\n```\n\n### Avoid Barrel Bloat and Circular Imports\n\nDo not create barrels that import everything at module load (they defeat tree-shaking and grow cold-start). Import concrete paths. Circular imports signal a submission boundary that should fold upward; the type that both sides need belongs in a shared module neither imports.\n\n### Split by Dependency Direction\n\nLet the type graph point the way: types that cross boundaries go in a contract module; implementations import the contract; nothing imports implementations from contracts. In a node\u002Fbackend codebase that means roughly: `domain` (pure types and rules) → `application` (use cases) → `infrastructure` (adapters), with dependencies pointing only inward.\n\n## Dependencies and Build\n\n### Diagnose, Then Add Dependencies\n\nPrefer built-in `Array`, `Map`, `Promise`, and `Intl` over pulling in utilities for every small operation. A tiny inline function beats a dependency that must be upgraded, audited, and kept compatible. (The Go idiom \"a little copying is better than a little dependency\" applies to TypeScript too.)\n\n### Runtime Validation, Not Type-of-Trust\n\nSchemas that validate at runtime (Zod, validators, or hand-written guards) are the bridge between untrusted data and compile-time types. Library approaches differ (Zod and other schema-first libraries derive the type from the schema; validators in some ecosystem patterns are type-first with the runtime check derived). Pick one model and be consistent across the codebase.\n\n### Keep the Compiler Incremental and Fast\n\nLarge codebases benefit from `composite: true` with project references, an `incremental` build cache, and `moduleResolution: bundler` where the bundler supports it. Slow type-checking is a workflow problem that pushes developers off the type system — invest in narrowing the checked surface over relaxing it.\n\n## Performance\n\n### Types Are Free, Structures Are Not\n\nType-level gymnastics (mapped types, conditional types, template literal types) cost nothing at runtime but can cost a lot of developer clarity. Keep complex type machinery inside boundary modules; do not export type circus acts as the public API.\n\n### Avoid Unnecessary Object Renaming\n\nCopying and spreading large nested objects repeatedly has real cost in hot paths. Prefer immutable updates with spread at the point of change, but avoid defensive re-copying of unchanged structures (for example, in render paths or per-message handlers).\n\n### Memoize Idempotent Computation\n\nPure, expensive derivations belong behind a cache if they repeat with the same inputs. Use `Map`-based caches with explicit lifetime instead of ad-hoc global caches that never clear.\n\n## Type-Level Testing\n\n### Assert the Types, Not Just the Runtime\n\nBehavior tests prove runtime behavior; dedicated type tests lock in the public API contract. A type that silently loosens is a regression.\n\n```typescript\nimport { expectTypeOf } from 'vitest'\n\nexpectTypeOf\u003CResult\u003CUser, ValidationIssue[]>>().toEqualTypeOf\u003C\n  | { ok: true; value: User }\n  | { ok: false; error: ValidationIssue[] }\n>()\n```\n\n### Use `satisfies` to Preserve Intent\n\n`satisfies` checks a value against a shape without widening it to that shape — the ideal way to keep literal types while still validating structure.\n\n```typescript\nconst statusByAction = {\n  new: 'open',\n  reopen: 'open',\n  close: 'closed'\n} as const satisfies Record\u003CAction, Status>\n```\n\n## TypeScript Tooling Integration\n\n### Essential Commands\n\n```bash\n# Type-check the whole project\nnpx tsc --noEmit\n\n# Watch mode for fast feedback\nnpx tsc --noEmit --watch\n\n# Run tests (Vitest)\nnpx vitest run\n\n# Lint with types-aware rules (typescript-eslint)\nnpx eslint .\n\n# Formatting\nnpx prettier --write .\n```\n\n### Recommended Linter Baseline\n\nThe `typescript-eslint` recommended-type-checked ruleset is the practical default: it promotes `no-unsafe-assignment`, `no-unsafe-member-access`, `no-unsafe-argument`, and `no-unsafe-call` from style noise to compiler-like guarantees. Keep the type-aware config; if it is slow, that is a project-structure signal, not a reason to disable it.\n\n## Anti-Patterns to Avoid\n\n- **`any` as a speed hack** — it converts the compiler's proof into a runtime guess. Reach for `unknown` + narrowing instead.\n- **`as` casts that lie** — a cast that bypasses a check you did not actually perform is where null-pointer and shape bugs are born. Validate, then cast, and keep the cast inside the module that validates.\n- **Deeply nested callbacks \u002F promise chains** — prefer async\u002Fawait; flat code is narrowable code.\n- **`enum` coercion bugs** — string-literal unions give you the same safety without runtime artifacts or reverse-mapping footguns.\n- **Giant god types** — a single interface that models several unrelated shapes should be a discriminated union or several interfaces.\n- **Optional-only option objects** — `allOptional` config types silently swallow typos at the call site; prefer required fields for the ones the function genuinely depends on.\n- **Silent catch** — `catch {}` or `catch (e) { \u002F* nothing *\u002F }` hides failures the caller assumed were handled.\n- **Mixing sync and async error paths** — an `async` function always surfaces throws as rejections, even before the first `await`. Only a non-`async` function returning a promise can throw synchronously (before returning it), forcing callers to handle two error shapes. Prefer `async` throughout so every failure is a rejection:\n\n```typescript\nasync function asyncFails(): Promise\u003Cnever> {\n  throw new Error('becomes a rejection, never a sync throw')\n}\n\nfunction lazyFails(): Promise\u003Cnever> {\n  throw new Error('throws synchronously — needs try\u002Fcatch AND .catch')\n}\n```\n\n**Remember**: the type system is a proof tool, not a paperwork burden. When a type error resists a reasonable annotation, the design — not the compiler — is usually the thing to change. Prefer boring, explicit, well-scoped TypeScript over clever type engines.\n\n## Related Skills\n\n- `nestjs-patterns` — NestJS architecture patterns for TypeScript backends (modules, controllers, providers, DTO validation)\n- `frontend-patterns` — React and Next.js component and state patterns\n- TypeScript rules (`rules\u002Ftypescript\u002F`, installed as `rules\u002Fecc\u002Ftypescript\u002F`) — the \"what\" and \"when\" this skill implements as the \"how\"\n- `prisma-patterns` — database access patterns used in TypeScript applications\n",{"name":5,"metadata":24,"description":7},{"origin":25},"ECC","main","7092b664627bf326748a6fcbf27fee6a34c4da1d","skills\u002Fstorage\u002Faffaan-m_ECC\u002Ftypescript-patterns",0,"https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills","https:\u002F\u002Fgithub.com\u002Fmdnaimul22","AI Agents Workflows Automation | Specializing in Python, FastAPI, MCP Agents & Custom ERP.","2026-11-11 21:16:57",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add mdnaimul22\u002Fhuman-skills --skill typescript-patterns",{"tool":40,"command":41},"bunx","bunx skills add mdnaimul22\u002Fhuman-skills --skill typescript-patterns",{"tool":43,"command":44},"pnpm","pnpm dlx skills add mdnaimul22\u002Fhuman-skills --skill typescript-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Ftypescript-patterns\u002FSKILL.md",true,[],[49,57,64,71,78,85],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":56},"01M767791C1KRP2ZRW2Z73VZ5Q","system-lifecycle-designer","Universal architectural methodology for designing granular, atomic, and sub-atomic lifecycles and end-to-end workflows for single functionality integrations across any domain (daemons, batch jobs, request transactions, resource pools). Provides patterns for deterministic identity, pre-commit validation, differential reconciliation, sticky leasing, state machines, transactional persistence, and closed-loop feedback.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fmy_skills\u002Fsystem-lifecycle-designer\u002FSKILL.md",[],[],"2026-11-12 13:55:43",{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":19},"01M748ABPN5F1FANHH6HKZQMXT","style-sampling","Make a new episode in a proven video style - Collage Explainer, Finance Explainer, Animated Science Explainer, 3D Brand Explainer, 3D True Crime - on the person's topic. Use for \"an episode of\", \"in the style of\", \"sample this style\", 「用这个风格做一集」. One video to copy is reverse-any-video.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fheygen-com_hyperframes\u002Fstyle-sampling\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M748A59V04PKW4HA0XQ81FGP","reverse-any-video","Rebuild any video file as an editable HyperFrames project - motion graphics, talking heads, live action or AI-generated footage - checked against the original frame by frame. Use to reverse, recreate, remake, replicate or copy a video, or 「复刻这个视频」「照着这个视频做一个」.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fheygen-com_hyperframes\u002Freverse-any-video\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M7487ERZRGPC5NJ75077Y238","test-collaboration","Inventory and govern a project's test assets. Connect requirements, business rules, risks, bugs, and cross-boundary contracts to stable TEST-IDs and executable evidence in the repository's existing test registry or TESTS.md. Use for test inventory, test gap analysis, unit\u002Fintegration\u002Fcontract\u002FE2E\u002Fsmoke classification, bug-to-test regression protection, consumer\u002Fprovider contract testing, test-necessity review, and pre-delivery evidence review.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Ftest-collaboration\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M748721J3GKR2WS6K0QWFC35","story-lifecycle","Manage a file-based epic → story → sprint development loop without requiring an external project management tool. Creates and tracks epics, breaks them into user stories, assigns them to sprints, and drives implementation story by story. Use when starting a new feature initiative or when the team has no Jira\u002FLinear\u002FTaiga but needs structured delivery tracking.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Fstory-lifecycle\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M7486VNZHNK4JAPWQXTDDT3J","skill-host-compat","Lint ECC skills for Codex\u002FCursor-safe frontmatter and Claude-only substitutions before a skill PR.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Fskill-host-compat\u002FSKILL.md",[],[]]