Clean Code Guidelines in TypeScript
🛠General Principles
- Readability over Cleverness: Write code that’s easy to understand, not just functional.
- Single Responsibility: Each function, class, or module should have one clear purpose.
- Avoid Duplication: Use abstractions to eliminate repetitive code (DRY principle).
- Type Safety: Leverage TypeScript’s strong type system to catch errors early.
✅ TypeScript-Specific Best Practices
1. Prefer Interfaces over Types
Use interface for describing data structures whenever possible:
interface User { id: number; name: string;}2. Use Enum for Constant Values
enum UserRole { Admin, User, Guest,}3. Always Type Function Parameters and Return Values
function getUserName(user: User): string { return user.name;}4. Avoid any Type
let data: unknown;🧹 Clean Functions
1. Keep Functions Small
A function should do only one thing.
function calculateDiscount(price: number, discount: number): number { return price * (1 - discount);}2. Use Descriptive Names
Avoid cryptic variable names.
// Badfunction x(y: number): number { return y * 2;}
// Goodfunction doubleValue(value: number): number { return value * 2;}3. Error Handling
Use try-catch for Error-Prone Operations
try { const data = await fetchData();} catch (error) { console.error("Error fetching data", error);}