Typescript rules

From Luohaothu/everything-codex · View interactive version

Typescript rules is an AI agent skill from the GitHub repository Luohaothu/everything-codex. Comprehensive TypeScript/JavaScript coding rules covering style, patterns, testing, and security

How to use this skill

Skill file

TypeScript/JavaScript Coding Rules

Coding Style

Immutability (CRITICAL)

ALWAYS create new objects, NEVER mutate existing ones:

Use spread operator for immutable updates:

// WRONG: Mutation
function updateUser(user, name) {
  user.name = name  // MUTATION!
  return user
}

// CORRECT: Immutability
function updateUser(user, name) {
  return {
    ...user,
    name
  }
}

File Organization

MANY SMALL FILES > FEW LARGE FILES:

Error Handling

ALWAYS handle errors comprehensively:

Use async/await with try-catch:

try {
  const result = await riskyOperation()
  return result
} catch (error) {
  console.error('Operation failed:', error)
  throw new Error('Detailed user-friendly message')
}

Input Validation

ALWAYS validate at system boundaries:

Use Zod for schema-based validation:

import { z } from 'zod'

const schema = z.object({
  email: z.string().email(),
  age: z.number().int().min(0).max(150)
})

const validated = schema.parse(input)

Console.log

Code Quality Checklist

Before marking work complete:

Patterns

Skeleton Projects

When implementing new functionality:

  1. Search for battle-tested skeleton projects
  2. Evaluate options for security, extensibility, relevance
  3. Clone best match as foundation
  4. Iterate within proven structure

Repository Pattern

Encapsulate data access behind a consistent interface:

interface Repository<T> {
  findAll(filters?: Filters): Promise<T[]>
  findById(id: string): Promise<T | null>
  create(data: CreateDto): Promise<T>
  update(id: string, data: UpdateDto): Promise<T>
  delete(id: string): Promise<void>
}

API Response Format

Use a consistent envelope for all API responses:

interface ApiResponse<T> {
  success: boolean
  data?: T
  error?: string
  meta?: {
    total: number
    page: number
    limit: number
  }
}

Custom Hooks Pattern

export function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value)

  useEffect(() => {
    const handler = setTimeout(() => setDebouncedValue(value), delay)
    return () => clearTimeout(handler)
  }, [value, delay])

  return debouncedValue
}

Testing

Minimum Test Coverage: 80%

Test Types (ALL required):

  1. Unit Tests - Individual functions, utilities, components
  2. Integration Tests - API endpoints, database operations
  3. E2E Tests - Critical user flows

Test-Driven Development

MANDATORY workflow:

  1. Write test first (RED)
  2. Run test - it should FAIL
  3. Write minimal implementation (GREEN)
  4. Run test - it should PASS
  5. Refactor (IMPROVE)
  6. Verify coverage (80%+)

Troubleshooting Test Failures

  1. Check test isolation
  2. Verify mocks are correct
  3. Fix implementation, not tests (unless tests are wrong)

E2E Testing

Use Playwright as the E2E testing framework for critical user flows.

Security

Mandatory Security Checks

Before ANY commit:

Secret Management

// NEVER: Hardcoded secrets
const apiKey = "sk-proj-xxxxx"

// ALWAYS: Environment variables
const apiKey = process.env.OPENAI_API_KEY

if (!apiKey) {
  throw new Error('OPENAI_API_KEY not configured')
}

Security Response Protocol

If security issue found:

  1. STOP immediately
  2. Fix CRITICAL issues before continuing
  3. Rotate any exposed secrets
  4. Review entire codebase for similar issues
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.