Static methods in TypeScript help you write cleaner, more efficient code by letting you create utility functions at the class level. You won’t need to create instances to use them, making them perfect for helper functions and shared operations.
Let’s explore how static methods work in TypeScript, with practical examples you can use right away.
Table of Contents
- What Are Static Methods?
- When Should You Use Static Methods?
- Static vs Instance Methods: What’s the Difference?
- Working with Static Properties
- How Inheritance Works with Static Methods
- Creating Factory Patterns
- Tips for Using Static Methods Well
- Watch Out For These Common Mistakes
- Advanced Examples
- Wrapping Up
What Are Static Methods?
Static methods belong to the class itself, not to individual instances. Think of them as standalone functions that live inside a class. They’re particularly useful when you need functions that don’t depend on instance-specific data.
class MathOperations {
static add(x: number, y: number): number {
return x + y;
}
static multiply(x: number, y: number): number {
return x * y;
}
}
// Just call them directly on the class
const sum = MathOperations.add(5, 3); // Gets you 8
const product = MathOperations.multiply(4, 2); // Gets you 8
Code language: PHP (php)
When Should You Use Static Methods?
Static methods shine in these situations:
- Helper Functions: When you need utility functions that work independently
- Factory Methods: For creating objects with specific setups
- Shared State: When you need to track information across all instances
- Singleton Patterns: For managing single-instance classes
Static vs Instance Methods: What’s the Difference?
Here’s a clear example showing how static and instance methods differ:
class Calculator {
private value: number;
constructor(initialValue: number) {
this.value = initialValue;
}
// Regular method - needs an instance
add(x: number): number {
this.value += x;
return this.value;
}
// Static method - use it directly
static sum(numbers: number[]): number {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
}
// Using a regular method
const calc = new Calculator(10);
calc.add(5); // Gets 15
// Using a static method
Calculator.sum([1, 2, 3, 4]); // Gets 10
Code language: JavaScript (javascript)
Working with Static Properties
Static methods can work with static properties to keep track of class-level information:
class Counter {
private static count: number = 0;
static increment(): number {
return ++Counter.count;
}
static getCount(): number {
return Counter.count;
}
static reset(): void {
Counter.count = 0;
}
}
Counter.increment(); // Returns 1
Counter.increment(); // Returns 2
Counter.getCount(); // Returns 2
Counter.reset(); // Sets it back to 0
Code language: JavaScript (javascript)
How Inheritance Works with Static Methods
Static methods get inherited by child classes, but there’s a twist:
class Parent {
static getClassName(): string {
return this.name;
}
}
class Child extends Parent {}
console.log(Parent.getClassName()); // Shows "Parent"
console.log(Child.getClassName()); // Shows "Child"
Code language: JavaScript (javascript)
Creating Factory Patterns
Static methods work great for factory patterns:
class Database {
private constructor(private connectionString: string) {}
static createConnection(config: {
host: string;
port: number;
database: string;
}): Database {
const connectionString = `mysql://${config.host}:${config.port}/${config.database}`;
return new Database(connectionString);
}
static createTestConnection(): Database {
return new Database('mysql://localhost:3306/test');
}
}
const prodDb = Database.createConnection({
host: 'production.server',
port: 3306,
database: 'myapp'
});
const testDb = Database.createTestConnection();
Code language: JavaScript (javascript)
Tips for Using Static Methods Well
1. Keep Them Simple and Pure
class StringUtils {
static capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
static reverse(str: string): string {
return str.split('').reverse().join('');
}
}
Code language: JavaScript (javascript)
2. Add Type Checking
class ValidationUtils {
static isString(value: unknown): value is string {
return typeof value === 'string';
}
static isNumber(value: unknown): value is number {
return typeof value === 'number' && !isNaN(value);
}
}
Code language: JavaScript (javascript)
3. Write Clear Documentation
class DateUtils {
/**
* Makes dates look nice and consistent
* @param date - Any valid date string
* @returns Date in YYYY-MM-DD format
*/
static formatDate(date: string): string {
const d = new Date(date);
return d.toISOString().split('T')[0];
}
}
Code language: JavaScript (javascript)
Watch Out For These Common Mistakes
- Don’t try to use instance properties in static methods – they can’t access them
- Remember that
this
in static methods points to the class itself - Don’t make everything static – use regular methods when working with instance data
Advanced Examples
Building a Singleton
class Singleton {
private static instance: Singleton;
private constructor() {}
static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
static resetInstance(): void {
Singleton.instance = null;
}
}
Code language: JavaScript (javascript)
Creating Utility Functions
class ArrayUtils {
static flatten<T>(arr: T[][]): T[] {
return arr.reduce((flat, current) => flat.concat(current), []);
}
static unique<T>(arr: T[]): T[] {
return Array.from(new Set(arr));
}
static groupBy<T>(arr: T[], key: keyof T): Record<string, T[]> {
return arr.reduce((groups, item) => {
const groupKey = String(item[key]);
groups[groupKey] = groups[groupKey] || [];
groups[groupKey].push(item);
return groups;
}, {} as Record<string, T[]>);
}
}
Code language: JavaScript (javascript)
Wrapping Up
Static methods make your TypeScript code cleaner and more organized. They’re great for utility functions and class-level operations. Remember to keep them simple, document them well, and use them only when they make sense for your code.
Want to learn more? Check out our guide on TypeScript Class Properties: A Complete Guide for more TypeScript tips and tricks.
Start using static methods in your projects today – they’ll help you write better, more organized code without unnecessary complexity.