DEV Community

Cover image for Stop Creating Useless Instances in TypeScript
Ramon Silva
Ramon Silva

Posted on

Stop Creating Useless Instances in TypeScript

Confess to me: how many times have you seen (or written) code where someone creates a class full of utility functions and, when it's time to use it, does a new CurrencyFormatter() just to call a method that formats a number?

Yeah. We often do this on autopilot, but in practice, we are allocating memory for a whole object without any real need.

If your function doesn't need to hold any internal "state" (meaning it doesn't use data from a specific instance), you don't need the new keyword. That's exactly what the static keyword is for.

Let's see the difference in practice.


❌ The useless new nightmare (Without static)

Imagine a simple utility class for formatting. If you don't use static, TypeScript forces you to instantiate the class (create an object) every single time you want to use its function:

class CurrencyFormatter {
  format(value: number) {
    return `$${value.toFixed(2)}`;
  }
}

// Wasting memory to create an object for no reason
const formatter = new CurrencyFormatter(); 
const result = formatter.format(150.5);
Enter fullscreen mode Exit fullscreen mode

✅ Straight to the point (With static)

class CurrencyFormatter {
  // The function now belongs to the class
  static format(value: number) {
    return `$${value.toFixed(2)}`;
  }
}

// No 'new', no mess. Direct call!
const result = CurrencyFormatter.format(150.5);
Enter fullscreen mode Exit fullscreen mode

🧠 Bonus: Sharing data across instances

The static keyword isn't just for utility functions. It's incredibly powerful for creating variables that need to be shared across all objects of that class.

Imagine you are processing transactions in a financial app and want to keep track of the total number of transactions created during a session. If you use a regular variable, each transaction will have its own isolated counter (which defeats the purpose). With static, the whole class shares the same variable:


class Transaction {
  // This value is shared across the entire application
  static totalProcessed = 0; 

  constructor(public amount: number) {
    // Every time a transaction is created, we update the global counter
    Transaction.totalProcessed++; 
  }
}

new Transaction(100);
new Transaction(50);
new Transaction(25);

console.log(Transaction.totalProcessed); // Output: 3
Enter fullscreen mode Exit fullscreen mode

The Golden Rule

Not sure if you should use it or not? Ask yourself this: "Does this method use the this keyword to access a variable that belongs only to this specific object?" If the answer is no, slap a static on it and be happy! Your code will be cleaner, more performant, and more professional.

Do you use static methods often in your projects, or do you still have the habit of throwing new at everything? Let me know in the comments!

Top comments (0)