TypeScript and JavaScript Best Practices for Node.js
Generate code that follows modern TypeScript and JavaScript best practices for Node.js applications, with emphasis on type safety, error handling, and avoiding common pitfalls.
Instructions
Follow these guidelines when generating TypeScript or JavaScript code:
1. API Usage
Use only officially supported JavaScript/TypeScript APIs and Node.js built-in modulesAvoid experimental, deprecated, or non-standard APIsVerify API availability in the target Node.js version before suggestingPrefer stable, documented APIs over cutting-edge featuresOnly suggest third-party libraries that are explicitly listed in `package.json`Prefer native language features over external utilities2. Type Safety (TypeScript)
Avoid `any` types and type assertions without justificationPrefer proper typing and type guards for unknown dataUse explicit return types for functionsValidate input parameters with proper type checksUse `satisfies` operator for type checking without wideningLeverage `Record<K, V>` for object types with known keysPrefer `const` assertions for immutable data3. Null and Undefined Safety
Use optional chaining (`?.`) for safe property accessUse nullish coalescing (`??`) for default valuesAvoid unsafe property access that could throw errorsCheck for null/undefined before operationsUse type guards for proper narrowing4. Error Handling
Always handle errors explicitly in async/await codeUse try-catch blocks with specific error handlingProvide meaningful error messagesType error objects properlyNever use empty catch blocks or generic error swallowingLog errors appropriately for debugging5. Async/Await Best Practices
Always await promises or handle them with `.catch()`Avoid Promise constructor anti-patternsUse async/await instead of raw promises when possibleHandle errors at appropriate levelsDon't mix callbacks with promises6. Array and Object Operations
Prefer immutable operations (map, filter, reduce) over mutationsUse spread operator for shallow copiesCheck array bounds before accessUse destructuring for cleaner codeAvoid modifying function parameters7. Variable Declarations
Use `const` by default for all variablesOnly use `let` when reassignment is necessaryNever use `var`Declare variables close to their usageUse meaningful, descriptive names8. Comparison Operations
Always use strict equality (`===`, `!==`)Never use loose equality (`==`, `!=`)Make boolean conversions explicitUse type guards for type-safe comparisons9. Memory Management
Remove event listeners when no longer neededClose resources (files, connections) in finally blocksClear timers and intervals when doneAvoid circular referencesConsider WeakMap/WeakSet for cache implementations10. Performance
Avoid expensive operations inside loopsCache computed values when appropriateUse early returns to avoid unnecessary workConsider lazy evaluation for expensive computationsProfile before optimizing11. Modern JavaScript/TypeScript Features
Prefer these modern features:
Optional chaining (`?.`)Nullish coalescing (`??`)Destructuring assignmentTemplate literalsArrow functions for pure, short functionsConst assertionsSatisfies operatorExamples
Good: Type-Safe Error Handling
```typescript
async function fetchUser(id: string): Promise<User | null> {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data: unknown = await response.json();
return parseUser(data);
} catch (error) {
if (error instanceof Error) {
console.error(`Failed to fetch user ${id}:`, error.message);
}
return null;
}
}
```
Good: Safe Property Access
```typescript
const userName = user?.profile?.name ?? 'Anonymous';
const firstItem = array?.[0];
```
Good: Immutable Operations
```typescript
const updatedItems = items.map(item => ({
...item,
processed: true
}));
```
Bad: Unsafe Code
```typescript
// ❌ Any type
function process(data: any) { }
// ❌ Unsafe property access
const name = user.profile.name;
// ❌ Loose equality
if (value == null) { }
// ❌ Ignored errors
try {
await riskyOperation();
} catch { }
// ❌ var declaration
var count = 0;
```
Pre-Submission Checklist
Before suggesting code, verify:
[ ] Only official APIs and standard library features are used[ ] All variables have appropriate types (TypeScript)[ ] Null/undefined safety is handled with `?.` and `??`[ ] Errors are properly caught, typed, and handled[ ] No memory leaks (event listeners, timers cleaned up)[ ] Functions have single responsibility[ ] No magic numbers or strings (use named constants)[ ] Async operations are properly awaited and error-handled[ ] Arrays/objects are not mutated unexpectedly[ ] Performance implications are considered[ ] Code follows modern JavaScript/TypeScript patterns[ ] `const` is used by default, `let` only when needed[ ] Strict equality (`===`) is used for comparisons