SkillAgentSearch skills...

ts

The best code style guide is the one your team already follows. This tool discovers it.

Install / Use

npx skills add zenbase-ai/context42

Installs into whichever agent you are using.

About this skill
📐

Cursor Rules

Cursor IDE rules (v2)

Quality Score

57/100

Supported Platforms

Cursor

description: ts Style Guide globs: "**/*.ts" alwaysApply: false

TypeScript Style Guide: Decoding the Developer's DNA

This guide captures the unique coding DNA of the developer, enabling AI agents to produce contributions indistinguishable from the original author. It focuses on the "how" and "why" behind the code, not just the "what."

1. CORE PHILOSOPHY

The developer prioritizes clarity, testability, modularity, reusability, and performance. Code is designed to be easily understood, independently verifiable, and composed of well-defined, single-responsibility units. There's a strong emphasis on predictable state management, robust error handling, and efficient resource management to ensure application stability and performance. Performance is a first-class citizen, particularly for I/O-bound tasks, but not at the expense of code readability or maintainability.

Rationale: This approach leads to a codebase that is resilient, maintainable, scalable, and performant, reducing cognitive load, preventing common pitfalls, and ensuring reliable resource utilization.

Examples:

  • Clarity & Modularity (across src/lib and test):

    // src/lib/cleanup-registry.ts
    class CleanupRegistry { /* ... */ }
    export const cleanupRegistry = new CleanupRegistry()
    
    // test/cleanup-registry.test.ts
    import { cleanupRegistry, createFileCleanupHandler } from "../src/lib/cleanup-registry.js"
    describe("CleanupRegistry", () => { /* ... */ })
    
    • NOT: A single large utility file containing all cleanup, database, and file exploration logic.
    • Rationale: Separates concerns into distinct modules, making each easier to understand, test, and maintain. This clear separation enhances maintainability and allows for easier independent development and testing of different application layers.
  • Testability & Predictable Behavior (evident in test files):

    // test/database.test.ts
    beforeEach(() => {
      testDb = new DB(":memory:") // In-memory DB for isolated tests
      testDb.init()
    })
    
    afterEach(() => {
      testDb.close() // Ensures clean state after each test
    })
    
    • NOT: Relying on a persistent database or shared global state that could lead to test interference.
    • Rationale: Guarantees that each test runs in a clean, isolated environment, preventing flaky tests and making failures easier to diagnose.
  • Robust Error Handling (across src/lib and test):

    // src/lib/cleanup-registry.ts
    unlink(file).catch(error => {
      if (error.code !== "ENOENT") {
        console.error(`Failed to clean up ${file}:`, error.message)
      }
    })
    
    // test/cleanup-registry.test.ts
    test("createFileCleanupHandler logs non-ENOENT errors", async () => {
      // ... mock unlink to throw ...
      const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {})
      const files = new Set(["/some/file.md"])
      const handler = createFileCleanupHandler(files)
      await handler()
      expect(consoleSpy).toHaveBeenCalledWith(
        "Failed to clean up /some/file.md:",
        "Permission denied"
      )
      consoleSpy.mockRestore()
    })
    
    • NOT: Ignoring potential errors or letting exceptions crash the application without specific handling or logging.
    • Rationale: Ensures that the application remains stable even when unexpected issues (like permission errors) occur, providing clear feedback for debugging.

2. NAMING PATTERNS

The developer employs a consistent and descriptive naming strategy, prioritizing clarity and context across both application and test code.

  • Camel Case for Variables, Functions, and Instances:

    • Pattern: camelCase for local variables, function names, and instances of classes.
    • Rationale: Standard JavaScript/TypeScript convention, enhances readability.
    • Examples:
      // src/lib/processor.ts
      const [progress, setProgress] = useState(0)
      const run = useCallback(async () => { /* ... */ })
      
      // test/cleanup-registry.test.ts
      let called = false
      const handler = () => { /* ... */ }
      
    • Anti-Example: Progress_Value, RUN_PROCESSOR, test_db.
  • Pascal Case for Classes, Types, and Interfaces:

    • Pattern: PascalCase for class definitions, interfaces, and custom types.
    • Rationale: Clear distinction between types/interfaces and runtime values, aligning with common TypeScript practices.
    • Examples:
      // src/lib/types.ts
      export type FileGroup = { /* ... */ }
      export class DB { /* ... */ }
      
      // test/database.test.ts
      let testDb: DB
      
    • Anti-Example: use_processor_options, worker.
  • Boolean Variables: Prefixed with is or has.

    • Example:
      // src/hooks/use-processor.ts
      const [isRunning, setIsRunning] = useState(false)
      
    • Anti-Example: processorRunning.
    • Rationale: Improves readability by immediately indicating a boolean type.
  • File Naming:

    • React Hooks: kebab-case prefixed with use-.
      • Example: use-processor.ts
      • Rationale: Consistent with React hook conventions, clearly identifies the file's purpose.
    • Library/Utility Files: kebab-case.
      • Example: cleanup-registry.ts, database.ts, explorer.ts
      • Rationale: Maintains consistency with file naming conventions across the project, promoting readability and discoverability.
  • Descriptive Prefixes/Suffixes for Test-Related Entities:

    • Pattern: test prefix for test-specific variables (e.g., testDb, testDir, testPath). Spy suffix for mocked console/function spies.
    • Rationale: Clearly indicates the purpose and scope of variables within a testing context, improving test readability.
    • Examples:
      // test/database.test.ts
      let testDb: DB
      
      // test/cleanup-registry.test.ts
      const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {})
      
    • Anti-Example: Generic names like db, directory, spy that lack context.
  • Clear and Concise Function/Method Names:

    • Pattern: Verbs or verb phrases that clearly describe the action performed (e.g., saveResponse, getChildStyleGuides, createFileCleanupHandler, generateStyleGuide, createStyleGuideProcessor).
    • Rationale: Improves code readability and makes the intent of the function immediately obvious.
    • Examples:
      // src/lib/database.ts
      this.database.prepare("INSERT INTO responses (run_id, result, created_at) VALUES (?, ?, ?)")
      
      // test/cleanup-registry.test.ts
      const handler = createFileCleanupHandler(files)
      
    • Anti-Example: Ambiguous names like processData, handleStuff, or doWork.

3. CODE ORGANIZATION

The codebase exhibits a strong commitment to modularity, clear separation of concerns, and a logical file structure, consistently applied across both application and test code.

  • Feature-Based Module Organization:

    • Pattern: Core functionalities are encapsulated within distinct modules (e.g., cleanup-registry, database, explorer, generator, processor) under a src/lib directory. Each module focuses on a single, well-defined responsibility. UI-specific logic (React hooks) resides in a hooks directory.
    • Rationale: Promotes high cohesion and low coupling, making modules easier to develop, test, and maintain independently. It also facilitates understanding the system's architecture at a glance.
    • Examples:
      // Project structure implies:
      src/
      ├── hooks/
      │   └── use-processor.ts
      └── lib/
          ├── cleanup-registry.ts
          ├── database.ts
          └── explorer.ts
      test/
      ├── cleanup-registry.test.ts
      ├── database.test.ts
      └── explorer.test.ts
      
    • Anti-Example: A monolithic utils.ts file containing unrelated functions, or scattering related logic across many unrelated files.
  • Dedicated Test Files per Module:

    • Pattern: Each source module (.ts in src/lib or src/hooks) has a corresponding test file (.test.ts) in the test/ directory.
    • Rationale: Ensures comprehensive testing for each functional unit and makes it easy to locate tests for a specific piece of code.
    • Examples:
      // test/cleanup-registry.test.ts tests ../src/lib/cleanup-registry.ts
      import { cleanupRegistry, createFileCleanupHandler } from "../src/lib/cleanup-registry.js"
      
      // test/database.test.ts tests ../src/lib/database.ts
      import { DB } from "../src/lib/database"
      
    • Anti-Example: A single all.test.ts file for all tests, or tests embedded directly within source files.
  • Consistent Import Ordering:

    • Pattern: Imports are grouped logically: Node.js built-in modules, then external libraries, then local relative imports, and finally type-only imports. Each group is typically separated by a blank line. Within groups, imports are generally ordered alphabetically.
    • Rationale: Provides a predictable and clean structure for dependencies, making it easy to scan and understand what external resources a file relies on.
    • Examples:
      // src/cli.ts
      import { homedir } from "node:os" // Node.js built-in
      import { cancel, intro, isCancel, multiselect, outro, spinner, text } from "@clack/prompts" // External libraries
      import { cleanupRegistry } from "./lib/cleanup-registry.js" // Local relative
      import type { FileGroup, Language } from "./lib/types.js" // Type-only
      
      // test/cleanup-registry.test.ts
      import { existsSync } from "node:fs" // Node.js built-in
      import { describe, test, expect, beforeEach, afterEach, vi } from "vitest" // External libraries
      import { cleanupRegistry, createFileCleanupHandler } from "../src/lib/cleanup-registry.js" // Local relative
      
    • Anti-Example: Random import order, or mixing different types of imports without clear separation.
  • Code Spacing and Indentation:

    • Indentation: 2 spaces.
    • Spacing: Consistent spacing around operators, after commas, and within object literals.
    • Example:
      // src/hooks/use-processor.ts
      const { model, concurrency, inputDir, onWorkerUpdate, fileGroups, outputDir } = options
      const [progress, setProgress] = useState(0)
      
    • Anti-Example: const {model,concurrency,inputDir}=options, const [ progress,setProgress ] = useState ( 0 ).
    • Rationale: Enhances visual clarity and readability, contributing to a consistent codebase appearance.
  • Bracket Placement:

    • Opening Brace: On the same line as the declaration (K&R style).
    • Example:
      // src/hooks/use-processor.ts
      export const useProcessor = (options: UseProcessorOptions): UseProcessorResult => {
        // ...
      }
      
    • Anti-Example: Opening brace on a new line.
    • Rationale: Common JavaScript/TypeScript convention, compacts code vertically.
  • **Logical Grouping within Files (especially

Truncated for display — read the full file on GitHub.

Related Skills

View on GitHub
GitHub Stars0
CategoryDevelopment
Updated7mo ago
Forks0

Security Score

74/100

Audited on Feb 14, 2026

1 medium2 low