Introduction to Object-Oriented Programming in TypeScript


Introduction

Object-Oriented Programming (OOP) is a paradigm that allows you to model real-world entities as objects with properties and behaviors. TypeScript, as a superset of JavaScript, supports OOP concepts. In this guide, we'll introduce you to the fundamental principles of OOP in TypeScript.


Classes and Objects

In OOP, a class is a blueprint for creating objects. Objects are instances of classes, and they have attributes (properties) and methods (functions).


Defining a Class

class Person {
firstName: string;
lastName: string;
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
getFullName() {
return this.firstName + " " + this.lastName;
}
}
const john = new Person("John", "Doe");

Properties and Methods

Properties are attributes that store data, while methods are functions that perform actions. You can access them using the dot notation.


Accessing Properties and Methods

console.log(john.firstName); // "John"
console.log(john.getFullName()); // "John Doe"

Inheritance

Inheritance is a key OOP concept that allows you to create a new class by inheriting properties and methods from an existing class. TypeScript supports single inheritance.


Extending a Class

class Student extends Person {
studentId: number;
constructor(firstName: string, lastName: string, studentId: number) {
super(firstName, lastName);
this.studentId = studentId;
}
getStudentInfo() {
return this.getFullName() + ", Student ID: " + this.studentId;
}
}
const alice = new Student("Alice", "Johnson", 12345);
console.log(alice.getStudentInfo()); // "Alice Johnson, Student ID: 12345"

Encapsulation

Encapsulation is the concept of bundling data (properties) and methods that operate on that data into a single unit (a class). It also involves controlling access to class members.


Access Modifiers

class BankAccount {
private balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
deposit(amount: number) {
this.balance += amount;
}
withdraw(amount: number) {
if (amount <= this.balance) {
this.balance -= amount;
}
}
getBalance() {
return this.balance;
}
}
const account = new BankAccount(1000);
account.deposit(500);
account.withdraw(200);
console.log(account.getBalance()); // 1300

Conclusion

Object-Oriented Programming is a powerful paradigm that helps organize and structure your code by modeling real-world entities as objects. TypeScript provides robust support for OOP concepts, including classes, inheritance, encapsulation, and more. As you continue your TypeScript journey, explore advanced OOP features and design patterns to create well-structured and maintainable applications.