TypeScript Class Functions
Methods that define object behavior
⚙️ What are Class Functions?
Class functions, also called methods, are functions defined inside a class that operate on object data. They define what actions objects can perform and how they behave, making classes interactive and functional.
// Class with methods
class Dog {
name: string;
constructor(name: string) {
this.name = name;
}
bark() {
return `${this.name} says Woof!`;
}
}
const myDog = new Dog("Buddy");
console.log(myDog.bark());
Output:
Buddy says Woof!
Method Types
Instance Methods
Work with object instances
class Counter {
increment() {
this.count++;
}
}
Static Methods
Called on the class itself
class Math {
static add(a, b) {
return a + b;
}
}
Getters
Access properties like variables
get fullName() {
return this.first + " " + this.last;
}
Setters
Modify properties with validation
set age(value: number) {
if (value > 0) this._age = value;
}
🔹 Instance Methods
Methods that work with individual object instances:
class BankAccount {
private balance: number = 0;
constructor(public accountHolder: string) {}
deposit(amount: number): void {
this.balance += amount;
console.log(`Deposited $${amount}`);
}
withdraw(amount: number): boolean {
if (amount <= this.balance) {
this.balance -= amount;
console.log(`Withdrew $${amount}`);
return true;
}
console.log("Insufficient funds");
return false;
}
getBalance(): number {
return this.balance;
}
}
const account = new BankAccount("John");
account.deposit(1000);
account.withdraw(300);
console.log(`Balance: $${account.getBalance()}`);
Output:
Deposited $1000
Withdrew $300
Balance: $700
🔹 Static Methods
Methods called on the class itself, not on instances:
class MathHelper {
static PI: number = 3.14159;
static add(a: number, b: number): number {
return a + b;
}
static multiply(a: number, b: number): number {
return a * b;
}
static circleArea(radius: number): number {
return this.PI * radius * radius;
}
}
// Call static methods on the class
console.log(MathHelper.add(5, 3));
console.log(MathHelper.multiply(4, 7));
console.log(MathHelper.circleArea(5));
Output:
8
28
78.53975
🔹 Getters and Setters
Control access to properties with getter and setter methods:
class Person {
private _age: number = 0;
constructor(
private firstName: string,
private lastName: string
) {}
// Getter
get fullName(): string {
return `${this.firstName} ${this.lastName}`;
}
// Setter
set fullName(name: string) {
const parts = name.split(' ');
this.firstName = parts[0];
this.lastName = parts[1];
}
get age(): number {
return this._age;
}
set age(value: number) {
if (value > 0 && value < 150) {
this._age = value;
} else {
console.log("Invalid age");
}
}
}
const person = new Person("John", "Doe");
console.log(person.fullName);
person.fullName = "Jane Smith";
console.log(person.fullName);
person.age = 30;
console.log(person.age);
Output:
John Doe
Jane Smith
30
🔹 Method Chaining
Return 'this' to enable chaining multiple method calls:
class StringBuilder {
private text: string = "";
append(str: string): this {
this.text += str;
return this;
}
prepend(str: string): this {
this.text = str + this.text;
return this;
}
toUpperCase(): this {
this.text = this.text.toUpperCase();
return this;
}
build(): string {
return this.text;
}
}
const result = new StringBuilder()
.append("World")
.prepend("Hello ")
.append("!")
.toUpperCase()
.build();
console.log(result);
Output:
HELLO WORLD!
🔹 Method Overloading
Define multiple signatures for the same method:
class Greeter {
// Method signatures
greet(name: string): string;
greet(firstName: string, lastName: string): string;
// Implementation
greet(firstName: string, lastName?: string): string {
if (lastName) {
return `Hello, ${firstName} ${lastName}!`;
}
return `Hello, ${firstName}!`;
}
}
const greeter = new Greeter();
console.log(greeter.greet("Alice"));
console.log(greeter.greet("Bob", "Smith"));
Output:
Hello, Alice!
Hello, Bob Smith!