In this TypeScript tutorial, we’ll explore the fundamentals of classes, an essential feature of object-oriented programming (OOP). By the end, you’ll have a solid understanding of how to create and use classes in TypeScript, along with practical code examples.
What are Classes?
In TypeScript, classes are a blueprint for creating objects with similar properties and methods. They provide a way to model real-world entities and encapsulate data and behavior into a single unit.
Creating a Class
Let’s start by creating a simple Person
class:
class Person {
// Properties
firstName: string;
lastName: string;
// Constructor
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
// Method
greet() {
console.log(`Hello, ${this.firstName} ${this.lastName}!`);
}
}
Instantiating Objects
Now, let’s create instances of the Person
class:
const person1 = new Person("John", "Doe");
const person2 = new Person("Jane", "Smith");
person1.greet(); // Output: Hello, John Doe!
person2.greet(); // Output: Hello, Jane Smith!
Inheritance
Classes in TypeScript support inheritance. Let’s create a Student
class that extends the Person
class:
class Student extends Person {
// Additional Properties
studentId: number;
// Constructor
constructor(firstName: string, lastName: string, studentId: number) {
super(firstName, lastName);
this.studentId = studentId;
}
// Method Override
greet() {
console.log(`Hello, ${this.firstName} ${this.lastName} (Student ID: ${this.studentId})!`);
}
}
Access Modifiers
TypeScript provides access modifiers (public
, private
, and protected
) to control the visibility of class members.
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;
} else {
console.log("Insufficient balance.");
}
}
}
Conclusion
In this TypeScript tutorial, we covered the basics of classes, including creating classes, instantiating objects, inheritance, and access modifiers. Classes are a powerful feature of TypeScript, allowing you to write clean, modular, and maintainable code.
Now that you’ve grasped the essentials, experiment with classes in your TypeScript projects to unlock their full potential!