Clean Code in TypeScript: Principles and Examples for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Clean Code in TypeScript: Principles and Examples for Beginners

Clean Code is not just a trendy term, but a development philosophy that helps you write programs that are understandable to other developers (and to yourself six months later). For beginner TypeScript programmers, mastering the principles of clean code is a key step towards professional growth. In this article, we will break down the basic rules, provide clear examples, and show you how to make your TypeScript code elegant and maintainable.



Why is Clean Code Important?

Imagine reading a book with no paragraphs, no punctuation, and all the words written together. That's roughly what messy code looks like to another developer. Clean code saves time on debugging, simplifies adding new features, and reduces the number of bugs. TypeScript, with its strict typing, already helps you write more reliable code, but without adhering to cleanliness principles, even typed code can become unreadable.



// Bad: unreadablefunction d(a:any,b:any){if(a>b){return a}else{return b}}

// Good: clean and clearfunction findMaxValue(firstNumber: number, secondNumber: number): number { if (firstNumber > secondNumber) { return firstNumber; } return secondNumber;}


Core Principles of Clean Code in TypeScript



1. Meaningful Variable and Function Names

A name should answer the questions "what?" and "why?". Avoid single-letter abbreviations (except for loop indices) and abstract names. Use camelCase for variables and PascalCase for classes.



// Badconst d = new Date();const arr = [1, 2, 3];function p(x: number) { return x * 2; }

// Goodconst currentDate = new Date();const numbersList: number[] = [1, 2, 3];function doubleValue(value: number): number { return value * 2;}


2. Functions Should Do Only One Thing

Each function should solve one task. If a function does more than one action, break it down into several smaller ones. This improves readability and testability.



// Bad: function does everything at oncefunction processUserData(userData: string): void {    const parsed = JSON.parse(userData);    const isValid = parsed.name && parsed.email;    if (isValid) {        console.log(`User ${parsed.name} registered`);        saveToDatabase(parsed);    }}

// Good: each function is responsible for its own taskfunction parseUserData(rawData: string): User { return JSON.parse(rawData);}

function validateUserData(user: User): boolean { return !!user.name && !!user.email;}

function registerUser(userData: string): void { const user = parseUserData(userData); if (validateUserData(user)) { console.log(`User ${user.name} registered`); saveToDatabase(user); }}


3. Avoid Magic Numbers and Strings

Magic numbers are literals whose meaning is unclear without context. Extract them into constants with clear names.



// Badif (user.age > 18) {    // ...}const discount = price * 0.1;

// Goodconst ADULT_AGE = 18;const STANDARD_DISCOUNT_RATE = 0.1;

if (user.age > ADULT_AGE) { // ...}const discount = price * STANDARD_DISCOUNT_RATE;


4. Use Types and Interfaces Correctly

TypeScript provides powerful tools for describing data. Don't overuse any; prefer specific types. Create interfaces for complex objects.



// Badfunction createUser(name: any, age: any) {    return { name, age, createdAt: new Date() };}

// Goodinterface User { name: string; age: number; createdAt: Date;}

function createUser(name: string, age: number): User { return { name, age, createdAt: new Date() };}

Blogs

Book Recommendations