10 Tricks to Write Super Clean Code in TypeScript
Tags: typescript, cleancode
Published: 2023-06-22 10:11:16

Writing clean and maintainable code is essential for any developer, regardless of their level of expertise. Clean code improves readability, enhances collaboration, and makes debugging easier. In the context of TypeScript, a statically-typed superset of JavaScript, clean code becomes even more important to take full advantage of the language's features. Whether you are a beginner or looking to improve your TypeScript skills, here are 10 tricks, along with examples, to help you write super clean code.

###  1. Use Descriptive Variable and Function Names:

```tsx
// Bad example
const x = 5;
const y = 10;

function fn(a: number, b: number): number {
  return a + b;
}

// Good example
const width = 5;
const height = 10;

function calculateArea(length: number, breadth: number): number {
  return length * breadth;
}

```

### 2. Follow Consistent Formatting and Indentation:

```tsx
// Bad example
function foo(){
console.log('Hello');
}

// Good example
function foo() {
  console.log('Hello');
}

```

### 3. Keep Functions Short and Focused:

```tsx
// Bad example
function processUserData(user: User) {
  // Perform user authentication
  // Retrieve user's data
  // Update user's profile
  // Send email notifications
}

// Good example
function authenticateUser(user: User) {
  // Perform user authentication
}

function retrieveUserData(user: User) {
  // Retrieve user's data
}

function updateUserProfile(user: User) {
  // Update user's profile
}

function sendEmailNotification(user: User) {
  // Send email notifications
}

```

### 4. Apply Strong Typing:

```tsx
// Bad example
function add(a, b) {
  return a + b;
}

// Good example
function add(a: number, b: number): number {
  return a + b;
}

```

### 5. Avoid Magic Numbers and Strings:

```tsx
// Bad example
function calculateTax(income: number): number {
  return income * 0.2;
}

// Good example
const TAX_RATE = 0.2;

function calculateTax(income: number): number {
  return income * TAX_RATE;
}

```

### 6. Utilize TypeScript's Interfaces and Types:

```tsx
// Bad example
function printUserDetails(user: any) {
  console.log(`Name: ${user.name}, Age: ${user.age}`);
}

// Good example
interface User {
  name: string;
  age: number;
}

function printUserDetails(user: User) {
  console.log(`Name: ${user.name}, Age: ${user.age}`);
}

```

### 7. Optimize Error Handling with TypeScript's Union Types:

```tsx
// Bad example
function fetchData(url: string): Promise<any> {
  return fetch(url)
    .then((response) => response.json())
    .catch((error) => {
      console.error('Error occurred:', error);
    });
}

// Good example
type FetchResult = { data: any } | { error: string };

async function fetchData(url: string): Promise<FetchResult> {
  try {
    const response = await fetch(url);
    const data = await response.json();
    return { data };
  } catch (error) {
    return { error: error.message };
  }
}

```

### 8. Apply Proper Code Comments:

```tsx
// Bad example
const result = a + b; // Add a and b

// Good example
const sum = a + b; // Calculate the sum of a and b

```

### 9. Eliminate Code Duplication with Functions and Helpers:

```tsx
// Bad example
function calculateArea(width: number, height: number): number {
  const area = width * height;
  console.log(`The area is ${area} square units.`);
  return area;
}

function calculatePerimeter(width: number, height: number): number {
  const perimeter = 2 * (width + height);
  console.log(`The perimeter is ${perimeter} units.`);
  return perimeter;
}

// Good example
function calculateArea(width: number, height: number): number {
  const area = width * height;
  return area;
}

function calculatePerimeter(width: number, height: number): number {
  const perimeter = 2 * (width + height);
  return perimeter;
}

function logResult(result: number, unit: string): void {
  console.log(`The ${unit} is ${result}.`);
}

const width = 5;
const height = 10;

const area = calculateArea(width, height);
logResult(area, 'area');

const perimeter = calculatePerimeter(width, height);
logResult(perimeter, 'perimeter');

```

### 10. Write Unit Tests:

```tsx
// Bad example
function add(a: number, b: number): number {
  return a + b;
}

// Good example
function add(a: number, b: number): number {
  return a + b;
}

// Unit test
test('add function', () => {
  expect(add(2, 3)).toBe(5);
  expect(add(-1, 1)).toBe(0);
});

```

By applying these 10 tricks, you'll be well on your way to writing super clean code in TypeScript. Remember, clean code is a mindset and a practice that requires ongoing effort. As you gain experience and work on larger projects, refining your coding style and following best practices will become second nature. Happy coding!