TypeScript/JavaScript Best Practices
Generate code that aligns with professional TypeScript and JavaScript standards, avoiding common issues and following modern best practices.
Instructions
General Guidelines
1. **Use only officially supported APIs**
- Only suggest officially supported JavaScript/TypeScript APIs and Node.js built-in modules
- Avoid experimental, deprecated, or non-standard APIs
- Verify API availability in the target Node.js version
- Prefer stable, documented APIs over cutting-edge features
2. **No unnecessary dependencies**
- Avoid suggesting third-party libraries unless explicitly listed in `package.json`
- Prefer native language features over external utilities
3. **Follow existing project patterns**
- Maintain consistency with the codebase's existing style and architecture
Type Safety (TypeScript)
Avoid `any` types and type assertions without clear justificationUse proper typing and type guards for unknown dataExplicitly declare function parameter types and return typesUse `satisfies` operator for type checking without type wideningLeverage `Record<K, V>` for object types with known keysApply `const` assertions for immutable data structuresNull/Undefined Safety
Always handle potential `null` or `undefined` valuesUse optional chaining (`?.`) for safe property accessUse nullish coalescing (`??`) for default valuesAvoid unsafe property access that could throw runtime errorsAdd explicit checks when optional chaining cannot be usedError Handling
Never ignore errors or use empty catch blocksProvide explicit error handling with proper typingInclude meaningful error messagesUse try-catch blocks for all async operationsType error objects appropriately (avoid `any` in catch blocks)Validate inputs at function boundariesAsync/Await Best Practices
Always `await` Promise-returning functionsAvoid Promise constructor anti-patterns (wrapping already-promised values)Handle errors comprehensively in async functionsConsider using `Promise.all()` for concurrent operationsClean up resources in `finally` blocks when neededArray and Object Operations
Prefer immutable operations (`map`, `filter`, `reduce`) over mutationAvoid direct mutation of arrays/objects unless intentionalUse safe array access patterns (check length, use optional chaining)Use destructuring assignment for cleaner codePrefer spreading (`...`) over `Object.assign()` for object compositionVariable Declarations
Use `const` by defaultUse `let` only when reassignment is necessaryNever use `var`Declare variables in the narrowest scope possibleAvoid declaring variables far from their usageComparison Operations
Always use strict equality (`===`, `!==`) instead of loose equality (`==`, `!=`)Use explicit boolean checks instead of relying on truthy/falsy conversionBe explicit about `null`, `undefined`, `0`, `""`, and `false` checksMemory Leak Prevention
Remove event listeners when components unmount or are no longer neededClear timers and intervals (`clearTimeout`, `clearInterval`)Close resources like file handles, database connections, and streamsUse `AbortController` for cancellable fetch requestsConsider WeakMap/WeakSet for cache implementationsPerformance Considerations
Avoid expensive operations inside loopsMemoize expensive computations when appropriateUse efficient algorithms and data structuresConsider lazy evaluation for expensive operationsAvoid unnecessary re-computation of valuesModern JavaScript/TypeScript Features
Prefer these modern features:
**Optional chaining** (`?.`) for safe property access**Nullish coalescing** (`??`) for default values**Destructuring assignment** for cleaner code**Template literals** instead of string concatenation**Arrow functions** for short, pure functions**Const assertions** (`as const`) for immutable data**Satisfies operator** for type checking without widening**Record<K, V>** for typed object mapsCode Review Checklist
Before generating code, verify:
[ ] Only official APIs and standard library features are used[ ] All variables have appropriate types (TypeScript)[ ] Null/undefined safety is properly handled[ ] Errors are caught and handled with meaningful messages[ ] No potential memory leaks (event listeners, timers, resources)[ ] Functions have single responsibility[ ] No magic numbers or strings (use named constants)[ ] Async operations are properly awaited with error handling[ ] Arrays/objects are not mutated unexpectedly[ ] Performance implications are considered[ ] Code follows existing project patterns and conventionsExamples
Good: Type-safe null handling
```typescript
function getUserEmail(user: User | null): string {
return user?.email ?? '[email protected]';
}
```
Good: Proper error handling
```typescript
async function fetchData(url: string): Promise<Data> {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
if (error instanceof Error) {
console.error('Fetch failed:', error.message);
}
throw error;
}
}
```
Good: Immutable array operations
```typescript
const activeUsers = users.filter(user => user.isActive);
const usernames = users.map(user => user.name);
```
Constraints
Do not suggest deprecated or experimental APIsDo not add external dependencies without explicit approvalDo not use `any` type without documented justificationDo not ignore error cases or use empty catch blocksDo not use `var` for variable declarationsDo not use loose equality operators (`==`, `!=`)