Object methods are key components in TypeScript that add functionality to your classes and objects. Let’s explore how to implement and use them effectively to write better, more maintainable code.
Table of Contents
- What Are Object Methods in TypeScript?
- Different Types of Methods
- Method Access Control
- Method Overloading
- Working with Async Methods
- Writing Better Methods
- Final Thoughts
What Are Object Methods in TypeScript?
Object methods are functions that live inside classes or objects. They define what your objects can do and how they behave. TypeScript adds type safety and excellent IDE support to help you catch errors before they happen.
class Calculator {
// A simple class method
add(a: number, b: number): number {
return a + b;
}
}
const calc = new Calculator();
console.log(calc.add(5, 3)); // Output: 8
Code language: JavaScript (javascript)
Different Types of Methods
Instance Methods
These are your everyday methods that work with specific instances of a class. Each object gets its own copy to work with its unique data.
class User {
private name: string;
constructor(name: string) {
this.name = name;
}
// Instance method
greet(): string {
return `Hello, ${this.name}!`;
}
}
const user = new User('John');
console.log(user.greet()); // Output: Hello, John!
Code language: JavaScript (javascript)
Static Methods
These methods belong to the class itself, not individual instances. They’re perfect for utility functions that don’t need specific instance data.
class MathUtils {
static square(x: number): number {
return x * x;
}
static isPositive(x: number): boolean {
return x > 0;
}
}
console.log(MathUtils.square(5)); // Output: 25
console.log(MathUtils.isPositive(-3)); // Output: false
Code language: JavaScript (javascript)
Getter and Setter Methods
These special methods control how you access and modify class properties:
class BankAccount {
private _balance: number = 0;
get balance(): number {
return this._balance;
}
set balance(amount: number) {
if (amount < 0) {
throw new Error('Balance cannot be negative');
}
this._balance = amount;
}
}
const account = new BankAccount();
account.balance = 100; // Using setter
console.log(account.balance); // Using getter, Output: 100
Code language: JavaScript (javascript)
Method Access Control
TypeScript lets you control who can access your methods:
class Employee {
private salary: number;
constructor(salary: number) {
this.salary = salary;
}
// Anyone can use public methods
public getAnnualSalary(): number {
return this.calculateMonthlyTotal() * 12;
}
// Only this class and its children can use protected methods
protected calculateMonthlyTotal(): number {
return this.salary + this.calculateBonus();
}
// Only this class can use private methods
private calculateBonus(): number {
return this.salary * 0.1;
}
}
Code language: JavaScript (javascript)
Method Overloading
Sometimes you want a method to handle different types of input. That’s where method overloading comes in:
class StringManipulator {
// Method overloads
repeat(str: string): string;
repeat(str: string, times: number): string;
repeat(str: string, times?: number): string {
const count = times ?? 1;
return str.repeat(count);
}
}
const manipulator = new StringManipulator();
console.log(manipulator.repeat('hello ')); // Output: hello
console.log(manipulator.repeat('hi ', 3)); // Output: hi hi hi
Code language: JavaScript (javascript)
Working with Async Methods
Need to handle asynchronous operations? Async methods have got you covered:
class DataFetcher {
async fetchUserData(id: number): Promise<any> {
try {
const response = await fetch(`https://api.example.com/users/${id}`);
return await response.json();
} catch (error) {
throw new Error(`Failed to fetch user data: ${error.message}`);
}
}
}
Code language: JavaScript (javascript)
Writing Better Methods
1. Keep Each Method Simple
A method should do one thing and do it well:
class Order {
// Good: Each method has one job
calculateSubtotal(): number {
// Just calculates subtotal
return 0;
}
calculateTax(): number {
// Just calculates tax
return 0;
}
// Bad: Trying to do too much
calculateTotalAndUpdateDatabase(): number {
// Don't mix calculations with database updates
return 0;
}
}
Code language: PHP (php)
2. Name Methods Clearly
class FileHandler {
// Good: Name tells you exactly what it does
async saveUserDataToFile(userData: UserData): Promise<void> {
// Implementation
}
// Bad: Name is too vague
async handle(data: any): Promise<void> {
// Implementation
}
}
Code language: JavaScript (javascript)
3. Always Specify Return Types
class NumberProcessor {
// Good: You know what you're getting back
processNumber(value: number): number {
return value * 2;
}
// Not great: Type is implicit
processString(value: string) {
return value.toUpperCase();
}
}
Code language: PHP (php)
Final Thoughts
Good TypeScript methods make your code easier to understand and maintain. They should be focused, well-named, and type-safe. When you write methods, think about how other developers will use them. Make them simple, clear, and predictable.
Want to learn more? Check out our guide on TypeScript Decorators vs Methods: Understanding Key Distinctions for advanced concepts.
Remember: The best methods are those that other developers can understand and use without having to peek at the implementation. Keep them simple, keep them focused, and your future self will thank you.