agentleFS
justanestajustanesta/claude-code-resources/skills/web_development/webdev-typescript-patterns/SKILL.md

webdev-typescript-patterns

Skill2 starsChanged 10 months agoMITView on GitHub

TypeScript 5.x type system patterns for production web development. Use this skill when writing TypeScript code, designing type-safe APIs, migrating from JavaScript, or building robust type architectures. Covers generics, utility types, discriminated unions, strict mode configuration, and declaration patterns.

The file

We split this skill into the rules it gives an agent

7 rules. About 0 are common, 2 are distinctive, and 5 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Type safety over convenience: - Avoid any; use unknown when the type is genuinely uncertain

    line 16
  2. Distinctive:

    Model domain states explicitly: - Use discriminated unions to make illegal states unrepresentable

    line 19
  3. Very specific:

    Use string literal unions instead of enum for simple value sets

    line 44
  4. Very specific:

    Prefer interface for object shapes that may be extended.

    line 45
  5. Very specific:

    Use readonly arrays and tuples to prevent mutation

    line 46
  6. Very specific:

    Add constraints with extends to communicate expectations

    line 85
  7. Distinctive:

    Use defaults for commonly assumed types

    line 86

≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

TypeScript Patterns

Production-ready TypeScript 5.x patterns emphasizing type safety, inference, and maintainability.

Core Principles

  1. Type safety over convenience - Avoid any; use unknown when the type is genuinely uncertain
  2. Enable strict mode from day one - All strict flags on; never selectively disable
  3. Prefer inference over annotation - Let TypeScript infer when the result is unambiguous
  4. Model domain states explicitly - Use discriminated unions to make illegal states unrepresentable
  5. Types are documentation - Well-named types replace comments and reduce cognitive load

Type System Fundamentals

Use unions, intersections, and literal types to model data precisely

// Literal types constrain to exact values
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";

// Intersection types compose capabilities
type Timestamped = { createdAt: Date; updatedAt: Date };
type SoftDeletable = { deletedAt: Date | null };
type BaseEntity = Timestamped & SoftDeletable & { id: string };

// Union types model alternatives
type Result<T> = { ok: true; value: T } | { ok: false; error: Error };

// Template literal types build string patterns
type EventName = `on${Capitalize<"click" | "focus" | "blur">}`;
// => "onClick" | "onFocus" | "onBlur"

Key rules:

  • Use string literal unions instead of enum for simple value sets
  • Prefer interface for object shapes that may be extended; type for unions and computed types
  • Use readonly arrays and tuples to prevent mutation

See type-system-patterns.md for:

  • Conditional types and infer keyword
  • Mapped types and key remapping
  • Template literal type utilities
  • Index signatures and record patterns

Generics

Use generics to write reusable, type-safe abstractions

// Constrained generic with default
interface Repository<T extends { id: string }, K extends keyof T = "id"> {
  findById(id: T[K]): Promise<T | null>;
  findAll(filter?: Partial<T>): Promise<T[]>;
  save(entity: Omit<T, "id">): Promise<T>;
}

// Generic function with inference
function groupBy<T, K extends string | number>(
  items: T[],
  keyFn: (item: T) => K
): Record<K, T[]> {
  return items.reduce((acc, item) => {
    const key = keyFn(item);
    (acc[key] ??= []).push(item);
    return acc;
  }, {} as Record<K, T[]>);
}

// Usage - types inferred from arguments
const grouped = groupBy(users, (u) => u.role);
// => Record<string, User[]>

Guidelines:

  • Name generics meaningfully: TItem, TResult, not just T for complex signatures
  • Add constraints with extends to communicate expectations
  • Use defaults for commonly assumed types

See generics-patterns.md for:

  • Generic component patterns for React
  • Builder and factory generics
  • Inference helpers and generic utilities
  • Variadic tuple types

Utility Types

Use built-in utility types to transform existing types

interface User {
  id: string;
  name: string;
  email: string;
  role: "admin" | "user";
}

// Partial for optional updates, Pick to select fields
type UserUpdate = Partial<Pick<User, "name" | "email">>;

// Omit to exclude, Required to enforce completeness
type UserCreate = Required<Omit<User, "id">>;

// Record for lookup maps, Extract/Exclude for filtering unions
type RolePermissions = Record<User["role"], string[]>;
type NonAdmin = Exclude<User["role"], "admin">; // "user"

Composition pattern: chain utilities to build precise types without repetition.

See utility-types.md for:

  • Custom utility type implementations
  • DeepPartial, DeepReadonly, and recursive types
  • Awaited, ReturnType, Parameters patterns
  • Branded and opaque types

Discriminated Unions and Type Guards

Use tagged unions to make state transitions explicit

type AsyncState<T> =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: T }
  | { status: "error"; error: Error };

function renderState<T>(state: AsyncState<T>): string {
  switch (state.status) {
    case "idle":
      return "Ready";
    case "loading":
      return "Loading...";
    case "success":
      return `Data: ${JSON.stringify(state.data)}`;
    case "error":
      return `Error: ${state.error.message}`;
  }
  // No default needed - TypeScript ensures exhaustiveness
}

// Custom type guard
function isNonNullable<T>(value: T): value is NonNullable<T> {
  return value !== null && value !== undefined;
}

const values = [1, null, 3, undefined, 5];
const clean: number[] = values.filter(isNonNullable);

See discriminated-unions.md for:

  • Exhaustive switch patterns with never
  • Type narrowing with in, instanceof, and custom guards
  • State machine modeling
  • Pattern matching utilities

Strict Mode Configuration

Always enable the full strict family in tsconfig.json

// tsconfig.json (essential strict options)
{
  "compilerOptions": {
    "strict": true,                    // Enables all strict checks
    "noUncheckedIndexedAccess": true,  // Array/object index returns T | undefined
    "exactOptionalProperties": true,   // Distinguishes missing vs undefined
    "verbatimModuleSyntax": true,      // Enforce explicit type-only imports
    "isolatedDeclarations": true       // 5.5+ parallel declaration emit
  }
}

See strict-mode-guide.md for:

  • Full tsconfig strict option reference
  • Migration strategy from JavaScript
  • Handling strictNullChecks in legacy code
  • Per-file @ts-expect-error migration patterns

Module and Declaration Patterns

Use explicit imports and declaration files for clean module boundaries

// Type-only imports keep runtime bundles lean
import type { User, UserCreate } from "./types.js";
import { createUser } from "./services.js";

// Declaration merging for third-party augmentation
declare module "express" {
  interface Request {
    user?: User;
    requestId: string;
  }
}

// Const assertion for immutable literal types
const ROUTES = {
  home: "/",
  users: "/users",
  settings: "/settings",
} as const;

type Route = (typeof ROUTES)[keyof typeof ROUTES];
// => "/" | "/users" | "/settings"

See declaration-patterns.md for:

  • Writing .d.ts declaration files
  • Module augmentation and global types
  • Ambient declarations for untyped libraries
  • Barrel exports and module organization

Anti-Patterns

AvoidUse Instead
any for unknown dataunknown with type guards
as type assertionsType narrowing with control flow
enum for string valuesString literal union types
Nested ternary type conditionalsHelper types with meaningful names
! non-null assertionsExplicit null checks or optional chaining
object or {} as a typeSpecific interface or Record<string, unknown>
Function typeExplicit signature (arg: T) => R
Disabling strict checksFixing the underlying type issue
@ts-ignore@ts-expect-error with explanation comment
Index signatures for known keysMapped types or explicit properties

Performance

Compilation and type-checking performance guidelines:

  • Project references - Split large codebases with composite: true for incremental builds
  • skipLibCheck: true - Skip type-checking .d.ts files to reduce build times
  • Isolate heavy types - Move complex conditional/mapped types to separate utility files
  • Avoid deeply recursive types - TypeScript caps recursion at ~50 levels; flatten where possible
  • Use isolatedDeclarations - Enables parallel declaration emit in TS 5.5+
  • tsc --noEmit in CI - Separate type-checking from bundling for faster feedback loops
  • Prefer interface over type for object shapes - Interfaces are internally cached more efficiently
  • Limit union breadth - Unions with 100+ members slow down assignability checks

source: TypeScript 5.x handbook, official documentation, and production best practices

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.