Regenerate all MDC rules with fresh Exa data and December 2025 best practices

- Refreshed all 241 library rules with current best practices
- Updated Exa search results for all libraries with 2025 content
- Fixed --regenerate-all flag logic to properly process all libraries
- Removed duplicate astro entry in rules.json (merged tags)
- Added missing docker.mdc and vim.mdc files
- All rules now include modern patterns and anti-patterns
- Updated with framework-specific recommendations for 2025

Technical improvements:
- Fixed retry_failed_only logic in generate_mdc_files.py
- Improved progress tracking for regeneration scenarios
- Ensured proper handling of --refresh-exa flag
This commit is contained in:
sanjeed5
2025-12-17 22:40:28 +05:30
parent 331fb6ffac
commit 8fbf269085
244 changed files with 66701 additions and 52708 deletions
+268 -217
View File
@@ -1,262 +1,313 @@
---
description: Enforces best practices for TypeScript development, including coding standards, performance considerations, and common pitfalls. This rule provides actionable guidance for developers to write clean, maintainable, and scalable TypeScript code.
globs: *.ts?(x)
description: Enforce modern TypeScript best practices for robust, type-safe JavaScript applications, focusing on strictness, clear type definitions, and runtime validation.
globs: **/*.{js,jsx}
---
# TypeScript Best Practices and Coding Standards
# TypeScript Best Practices (for JS/JSX Type-Checking)
This document outlines best practices and coding standards for developing TypeScript applications. Following these guidelines will help ensure code quality, maintainability, and scalability.
This guide outlines essential TypeScript best practices for teams working with JavaScript or JSX files that are type-checked by TypeScript (e.g., via `tsconfig.json` with `allowJs` and/or JSDoc annotations). While many examples use native TypeScript syntax for clarity and conciseness, the underlying principles and type-safety benefits apply directly to your `.js`/`.jsx` codebase.
## 1. Code Organization and Structure
## 1. Enable Strict Mode in `tsconfig.json`
- **Directory Structure:**
- **Feature-based:** Group files related to a specific feature within a dedicated directory.
src/
├── feature1/
│ ├── components/
│ │ ├── ComponentA.tsx
│ │ └── ComponentB.tsx
│ ├── services/
│ │ └── feature1.service.ts
│ ├── types.ts
│ └── feature1.module.ts
├── feature2/
│ └── ...
└── shared/
├── components/
│ └── ReusableComponent.tsx
├── services/
│ └── api.service.ts
└── types/
└── global.d.ts
- **Type-based:** Separate files based on their role (components, services, types, etc.).
src/
├── components/
│ ├── Feature1Component.tsx
│ └── Feature2Component.tsx
├── services/
│ ├── feature1.service.ts
│ └── feature2.service.ts
├── types/
│ ├── feature1.types.ts
│ └── feature2.types.ts
└── modules/
├── feature1.module.ts
└── feature2.module.ts
- Choose the structure that best fits your project's complexity and team's preferences. Consistency is key.
This is the single most impactful change you can make. `strict: true` enables a suite of crucial checks that catch the vast majority of common type-related bugs at compile time.
- **File Naming Conventions:**
- Use descriptive and consistent file names.
- Components: `ComponentName.tsx`
- Services: `serviceName.service.ts`
- Types: `typeName.types.ts` or `types.ts` (if grouping related types)
- Modules: `moduleName.module.ts`
- Interfaces: `IInterfaceName.ts` (or `interfaceName.interface.ts` if preferred and consistent throughout the codebase)
**Action**: Ensure your `tsconfig.json` includes:
- **Module Organization:**
- Use ES Modules (`import`/`export`) for modularity and reusability.
- Favor named exports over default exports for better discoverability and refactoring.
- Group related functionality into modules.
- Avoid circular dependencies.
```json
// tsconfig.json
{
"compilerOptions": {
"strict": true, // Enables all strict type-checking options
"noImplicitAny": true, // Catches untyped variables/parameters
"strictNullChecks": true, // Prevents `null`/`undefined` access without checks
"strictPropertyInitialization": true, // Ensures class properties are initialized
"allowJs": true, // Crucial for type-checking .js/.jsx files
"checkJs": true, // Enables type-checking in .js/.jsx files
// ... other options
},
"include": ["**/*.js", "**/*.jsx"] // Ensure your JS/JSX files are included
}
```
- **Component Architecture:**
- Consider using component-based architectures like React, Angular, or Vue.js.
- Follow component design principles: Single Responsibility Principle, separation of concerns.
- Use composition over inheritance.
- Keep components small and focused.
## 2. Define Clear Type Contracts
- **Code Splitting Strategies:**
- Split your application into smaller chunks to improve initial load time.
- Implement lazy loading for modules and components that are not immediately needed.
- Use dynamic imports (`import()`).
- Webpack, Parcel, and other bundlers offer built-in support for code splitting.
Use interfaces and type aliases to describe the shape of your data, especially for API payloads, component props, and complex objects. For `.js`/`.jsx` files, leverage JSDoc to apply these types.
## 2. Common Patterns and Anti-patterns
### ✅ GOOD: Interfaces for Object Shapes & Classes
- **Design Patterns:**
- **Factory Pattern:** Use factories to create objects with complex initialization logic.
- **Singleton Pattern:** Use sparingly, and only when a single instance is truly required.
- **Observer Pattern:** Implement reactive patterns for handling events and data changes.
- **Strategy Pattern:** Define a family of algorithms and encapsulate each one into a separate class.
- **Dependency Injection:** Reduce coupling by injecting dependencies into components and services.
Interfaces are ideal for defining the shape of objects and for implementing explicit contracts when working with classes. Define these in `.d.ts` or `.ts` files, then reference them in JSDoc.
- **Recommended Approaches:**
- **Data Fetching:** Use libraries like `axios` or `fetch` for making API requests.
- **State Management:** Choose a state management solution appropriate for your application's complexity (e.g., React Context, Redux, Zustand, MobX).
- **Form Handling:** Use libraries like `react-hook-form` or `formik` for managing form state and validation.
```typescript
// types.d.ts or types.ts
interface UserProfile {
id: string;
name: string;
email: string;
age?: number; // Optional property
}
- **Anti-patterns and Code Smells:**
- **`any` type overuse:** Avoid using `any` as much as possible. Use more specific types or generics.
- **Long methods/functions:** Break down large functions into smaller, more manageable units.
- **Deeply nested code:** Refactor deeply nested code to improve readability.
- **Magic numbers/strings:** Use constants for values that have a specific meaning.
- **Duplicated code:** Extract common logic into reusable functions or components.
- **Ignoring errors:** Always handle errors gracefully. Don't just catch and ignore them.
- **Over-commenting:** Write self-documenting code and use comments only when necessary to explain complex logic.
interface Point {
readonly x: number;
readonly y: number;
}
```
- **State Management Best Practices:**
- Choose a state management library based on project needs: React Context API, Redux, Zustand, MobX.
- Keep state minimal and derive values where possible.
- Follow immutable update patterns (especially with Redux).
- Use selectors to access state.
- Centralize state logic.
```javascript
// user-service.js
/**
* @typedef {import('./types').UserProfile} UserProfile
*/
- **Error Handling Patterns:**
- Use `try...catch` blocks to handle potential errors.
- Implement a global error handler to catch unhandled exceptions.
- Use error logging to track errors in production.
- Use discriminated unions for representing different error states.
- Implement retry mechanisms for transient errors.
/**
* @param {UserProfile} user
* @returns {string}
*/
export function greetUser(user) {
return `Hello, ${user.name}!`;
}
```
## 3. Performance Considerations
### ✅ GOOD: Type Aliases for Complex Types & Unions
- **Optimization Techniques:**
- **Memoization:** Use memoization techniques (e.g., `React.memo`, `useMemo`) to avoid unnecessary re-renders.
- **Debouncing and Throttling:** Limit the rate at which functions are executed in response to user input.
- **Virtualization:** Use virtualization for rendering large lists or tables.
- **Code Splitting:** Split your code into smaller chunks to reduce initial load time.
Type aliases are powerful for defining unions, intersections, primitive aliases, and tuples. Define these in `.d.ts` or `.ts` files, then reference them in JSDoc.
- **Memory Management:**
- Avoid memory leaks by properly cleaning up resources (e.g., event listeners, timers).
- Use weak references to avoid circular dependencies that can prevent garbage collection.
- Profile your application to identify memory leaks.
```typescript
// types.d.ts or types.ts
type ID = string | number;
type UserRole = "admin" | "user" | "guest"; // Strict literal type
type Coords = [number, number];
```
- **Rendering Optimization:**
- Minimize DOM manipulations.
- Use CSS transforms and animations instead of JavaScript animations.
- Optimize images and other assets.
- Use the `shouldComponentUpdate` lifecycle method or `React.memo` to prevent unnecessary re-renders.
```javascript
// auth-service.js
/**
* @typedef {import('./types').ID} ID
* @typedef {import('./types').UserRole} UserRole
*/
- **Bundle Size Optimization:**
- Use tree shaking to remove unused code from your bundle.
- Minify your code to reduce bundle size.
- Compress your code using gzip or Brotli.
- Use code splitting to load only the code that is needed for a particular page or component.
/**
* @param {ID} userId
* @param {UserRole} role
* @returns {void}
*/
export function assignRole(userId, role) {
console.log(`User ${userId} assigned role: ${role}`);
}
```
- **Lazy Loading Strategies:**
- Lazy load modules and components that are not immediately needed.
- Use dynamic imports (`import()`) to load modules on demand.
- Implement a loading indicator to provide feedback to the user while the module is loading.
## 3. Avoid `any` and Prefer `unknown` for Untyped Data
## 4. Security Best Practices
`any` completely bypasses TypeScript's checks, reintroducing JavaScript's runtime errors. `unknown` is a safer alternative that forces you to narrow the type before use.
- **Common Vulnerabilities and Prevention:**
- **Cross-Site Scripting (XSS):** Sanitize user input and escape output to prevent XSS attacks.
- **Cross-Site Request Forgery (CSRF):** Use anti-CSRF tokens to protect against CSRF attacks.
- **SQL Injection:** Use parameterized queries or ORMs to prevent SQL injection attacks (relevant for backend TypeScript).
- **Denial of Service (DoS):** Implement rate limiting and other measures to prevent DoS attacks.
- **Man-in-the-Middle (MitM):** Use HTTPS to encrypt communication between the client and server.
### ❌ BAD: Using `any`
- **Input Validation:**
- Validate all user input on both the client and server sides.
- Use strong validation rules to prevent malicious input.
- Sanitize user input to remove potentially harmful characters.
```javascript
// data-processor.js
/**
* @param {any} data // Bypasses all type checks
*/
export function processDataBad(data) {
// No type safety here, data.foo might not exist
console.log(data.foo.bar);
}
```
- **Authentication and Authorization Patterns:**
- Use a secure authentication mechanism to verify user identities.
- Implement authorization checks to control access to resources.
- Use role-based access control (RBAC) to manage user permissions.
- Use JSON Web Tokens (JWT) for stateless authentication.
### ✅ GOOD: Using `unknown` (and Type Guards)
- **Data Protection Strategies:**
- Encrypt sensitive data at rest and in transit.
- Use strong encryption algorithms.
- Store passwords securely using a hashing algorithm and salt.
- Protect API keys and other secrets.
When dealing with data from external sources (e.g., API responses), use `unknown` and then narrow its type using runtime checks.
- **Secure API Communication:**
- Use HTTPS for all API communication.
- Implement proper authentication and authorization for API endpoints.
- Use rate limiting to prevent abuse.
- Validate API requests and responses.
```javascript
// data-processor.js
/**
* @param {unknown} data // Forces runtime checks
*/
export function processDataGood(data) {
if (typeof data === 'object' && data !== null && 'foo' in data) {
/** @type {{ foo: { bar: string } }} */
const typedData = data; // Type assertion after narrowing
console.log(typedData.foo.bar);
} else {
console.error('Invalid data structure');
}
}
```
## 5. Testing Approaches
## 4. Implement Robust Runtime Type Validation (Type Guards)
- **Unit Testing Strategies:**
- Write unit tests for individual functions and components.
- Use mocking and stubbing to isolate units of code.
- Test edge cases and error conditions.
- Aim for high code coverage.
TypeScript's compile-time checks are erased at runtime. For data from external sources (APIs, user input), you *must* perform runtime validation to prevent crashes.
- **Integration Testing:**
- Test the interaction between different modules and components.
- Verify that different parts of the application work together correctly.
### ✅ GOOD: `typeof` for Primitives
- **End-to-End Testing:**
- Test the entire application from the user's perspective.
- Use tools like Cypress or Playwright to automate end-to-end tests.
```javascript
// utils.js
/**
* @param {unknown} value
* @returns {boolean}
*/
export function isString(value) {
return typeof value === 'string';
}
- **Test Organization:**
- Organize tests in a way that makes it easy to find and run them.
- Group tests by feature or module.
- Use descriptive test names.
/**
* @param {unknown} value
* @returns {boolean}
*/
export function isNumber(value) {
return typeof value === 'number' && !isNaN(value);
}
```
- **Mocking and Stubbing:**
- Use mocking and stubbing to isolate units of code and simulate dependencies.
- Use mocking libraries like Jest or Sinon.js.
### ✅ GOOD: Custom Type Guards for Complex Objects
## 6. Common Pitfalls and Gotchas
For interfaces or complex object shapes, create custom functions that perform runtime checks and act as type predicates.
- **Frequent Mistakes:**
- Incorrectly handling asynchronous operations (Promises, async/await).
- Not handling errors properly.
- Overusing the `any` type.
- Ignoring compiler warnings.
- Not keeping dependencies up to date.
```typescript
// types.d.ts or types.ts
interface Product {
id: string;
name: string;
price: number;
}
- **Edge Cases:**
- Handling different browser versions and devices.
- Dealing with network latency and failures.
- Handling different time zones and locales.
- Handling large datasets and complex calculations.
// Custom type guard (can be in a .ts file, or its logic used directly in .js)
/**
* @param {unknown} obj
* @returns {obj is Product}
*/
function isProduct(obj) {
return (
typeof obj === 'object' && obj !== null &&
'id' in obj && typeof obj.id === 'string' &&
'name' in obj && typeof obj.name === 'string' &&
'price' in obj && typeof obj.price === 'number'
);
}
```
- **Version-Specific Issues:**
- Be aware of breaking changes in new versions of TypeScript and related libraries.
- Consult the release notes for each new version to identify potential issues.
- Use TypeScript's compiler options to target specific ECMAScript versions and maintain backwards compatibility if needed.
```javascript
// api-client.js
/**
* @typedef {import('./types').Product} Product
* @type {typeof import('./types').isProduct}
*/
import { isProduct } from './types'; // Assuming isProduct is exported from types.ts/d.ts
- **Compatibility Concerns:**
- Ensure that your code is compatible with the target browsers and devices.
- Use polyfills to provide support for older browsers.
- Test your code on different platforms to identify compatibility issues.
/**
* @param {unknown} apiResponse
*/
export function handleApiResponse(apiResponse) {
if (isProduct(apiResponse)) {
// TypeScript now knows apiResponse is Product here
console.log(`Fetched product: ${apiResponse.name} at $${apiResponse.price}`);
} else {
console.error('API response is not a valid Product:', apiResponse);
}
}
```
- **Debugging Strategies:**
- Use a debugger to step through your code and inspect variables.
- Use console logging to track the flow of execution and identify errors.
- Use TypeScript's type checking to catch errors early.
- Use source maps to debug code that has been transpiled or minified.
- Learn to read and understand stack traces.
## 5. Prefer Union Types over Traditional Enums
## 7. Tooling and Environment
For simple sets of related constants, strict literal union types (`"admin" | "user"`) are generally preferred over TypeScript's `enum` keyword because they offer better type safety and simpler runtime representation. If you must use enums, prefer `const enum` or string enums.
- **Recommended Development Tools:**
- **IDE:** Visual Studio Code with the TypeScript extension.
- **Package Manager:** npm or Yarn.
- **Bundler:** Webpack, Parcel, or Rollup.
- **Linter:** ESLint with TypeScript-specific rules.
- **Formatter:** Prettier.
- **Testing Framework:** Jest, Mocha, or Jasmine.
### ❌ BAD: Numeric Enums
- **Build Configuration:**
- Use a `tsconfig.json` file to configure the TypeScript compiler.
- Configure compiler options like `target`, `module`, `jsx`, and `strict`.
- Use TypeScript's project references to organize large projects.
```typescript
// In a .ts file or JSDoc
enum UserStatus {
Active, // 0
Inactive, // 1
Pending // 2
}
// Problem: Can be assigned any number at runtime, e.g., UserStatus.Active = 99
```
- **Linting and Formatting:**
- Use ESLint with TypeScript-specific rules to enforce coding standards.
- Use Prettier to automatically format your code.
- Integrate linting and formatting into your development workflow using Git hooks or CI/CD pipelines.
### ✅ GOOD: String Literal Unions or `const enum`
- **Deployment Best Practices:**
- Use a build process to transpile and bundle your code.
- Minify and compress your code to reduce bundle size.
- Use a CDN to serve static assets.
- Implement caching strategies to improve performance.
```typescript
// types.d.ts or types.ts
/** @typedef {'active' | 'inactive' | 'pending'} UserStatus */
// Or using native TS:
type UserStatus = 'active' | 'inactive' | 'pending';
- **CI/CD Integration:**
- Integrate your tests and linters into your CI/CD pipeline.
- Automate the build and deployment process.
- Use environment variables to configure your application for different environments.
// If an enum is truly necessary, use a const string enum for compile-time safety and runtime efficiency:
const enum UserRole {
Admin = "admin",
User = "user",
Guest = "guest",
}
```
```javascript
// user-management.js
/**
* @typedef {import('./types').UserStatus} UserStatus
*/
/**
* @param {UserStatus} status
*/
export function updateUserStatus(status) {
console.log(`User status updated to: ${status}`);
}
updateUserStatus('active');
// updateUserStatus('invalid'); // Type error
```
## 6. Use Generics for Reusable Components/Functions
Generics allow you to write flexible and reusable code that works with a variety of types while maintaining type safety.
```javascript
// utils.js
/**
* @template T
* @param {T} arg
* @returns {T}
*/
export function identity(arg) {
return arg;
}
const num = identity(123); // num is inferred as number
const str = identity("hello"); // str is inferred as string
// With constraints (requires native TS syntax or complex JSDoc)
// For complex generics with constraints, consider writing them in a .ts file
// and importing their JSDoc type definitions.
```
## 7. Enforce Consistent Code Organization
Maintainable codebases rely on clear structure.
### ✅ GOOD: Named Exports (No Default Exports)
Named exports promote explicit imports and make refactoring easier. Avoid default exports entirely.
```javascript
// user-service.js
// ❌ BAD: default export
// export default class UserService { /* ... */ }
// ✅ GOOD: named export
export class UserService { /* ... */ }
export const DEFAULT_USER = { /* ... */ };
```
### ✅ GOOD: Organized Imports
Group imports by type (e.g., library, absolute path, relative path) and sort them alphabetically. Use path aliases for cleaner imports from deeply nested modules.
```javascript
// some-component.jsx
import React from 'react'; // Library imports
import { useSelector } from 'react-redux';
import { API_URL } from 'config/constants'; // Absolute imports (e.g., using path aliases)
import { selectUser } from 'store/selectors';
import { Button } from './components/Button'; // Relative imports
import { formatCurrency } from '../utils/formatters';
```
##