Raw view: TypeScript

No invisible, zero-width, or bidi-control characters detected.

---
description: TypeScript coding standards for strict, type-safe application code.
globs: "**/*.{ts,tsx}"
alwaysApply: false
---
# TypeScript Best Practices

## Type System
- Prefer interfaces for object shapes that may be extended; use `type` for unions, intersections, and mapped types
- Avoid `any`; use `unknown` for values of unknown shape and narrow before use
- Enable `strict` (and consider `noUncheckedIndexedAccess`) in `tsconfig.json`
- Leverage built-in utility types (`Partial`, `Pick`, `Omit`, `Record`, `ReturnType`)
- Use generics for reusable type patterns; keep type parameters minimal and constrained
- Use `satisfies` to check an object against a type without widening it
- Prefer `as const` (or `const` type parameters) over `enum` for fixed sets of values

## Naming Conventions
- Use PascalCase for type names and interfaces
- Use camelCase for variables and functions
- Use UPPER_CASE for module-level constants
- Use descriptive names with auxiliary verbs (e.g., `isLoading`, `hasError`)
- Suffix React prop interfaces with `Props` (e.g., `ButtonProps`)

## Code Organization
- Keep type definitions close to where they're used
- Export shared types from dedicated type files
- Use barrel exports (`index.ts`) sparingly; they can hurt tree-shaking and create import cycles
- Co-locate component props with their components

## Functions
- Use explicit return types for exported functions
- Use arrow functions for callbacks; use regular methods on classes unless you need lexical `this`
- Use function overloads only when a union or generic cannot express the signature
- Prefer `async`/`await` over raw Promise chains

## Best Practices
- Use `readonly` for properties that should not change after construction
- Model state with discriminated unions instead of optional flags
- Use type guards (`x is T`) for runtime narrowing
- Handle `null` and `undefined` explicitly; do not use the non-null assertion `!` to silence the compiler
- Avoid type assertions (`as`) unless you have verified the value at runtime

## Error Handling
- Create custom error classes for domain-specific errors
- Use `Result` types (`{ ok: true, value } | { ok: false, error }`) for expected failures
- Treat caught errors as `unknown` and narrow before use
- Handle Promise rejections; never leave a floating promise

## Patterns
- Reach for plain functions and modules first; add classes or dependency injection only when the code needs them