DEV Community

Cover image for 10 Tricks to Write Super Clean Code in TypeScript
Ryan Aulia
Ryan Aulia

Posted on • Edited on • Originally published at aulianza.id

10 Tricks to Write Super Clean Code in TypeScript

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:

// 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;
}

Enter fullscreen mode Exit fullscreen mode

2. Follow Consistent Formatting and Indentation:

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

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

Enter fullscreen mode Exit fullscreen mode

3. Keep Functions Short and Focused:

// 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
}

Enter fullscreen mode Exit fullscreen mode

4. Apply Strong Typing:

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

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

Enter fullscreen mode Exit fullscreen mode

5. Avoid Magic Numbers and Strings:

// 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;
}

Enter fullscreen mode Exit fullscreen mode

6. Utilize TypeScript's Interfaces and Types:

// 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}`);
}

Enter fullscreen mode Exit fullscreen mode

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

// 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 };
  }
}

Enter fullscreen mode Exit fullscreen mode

8. Apply Proper Code Comments:

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

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

Enter fullscreen mode Exit fullscreen mode

9. Eliminate Code Duplication with Functions and Helpers:

// 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');

Enter fullscreen mode Exit fullscreen mode

10. Write Unit Tests:

// 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);
});

Enter fullscreen mode Exit fullscreen mode

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!

Top comments (1)

Collapse
 
aulianza profile image
Ryan Aulia

Hi, kindly leave a like and comment if you got something to ask! 🔥