Skip to main content

Object-Oriented Programming in Typescript

Introduction

This tutorial will introduce you to Object-Oriented Programming (OOP) in Typescript. Designed to provide a simple yet comprehensive overview, it's perfect for beginners. So, let's dive in!

What is Object-Oriented Programming (OOP)?

Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of "objects". These objects are instances of classes, which can hold values, and methods, which are functions that belong to a specific class.

Basic Principles of OOP in Typescript

Classes

Class is a blueprint from which we can create objects that share the same configuration - properties and methods. Here's how you can define a class in Typescript:

class Car {
constructor(public color: string, public model: string) {}
}

You can then create an object of this class like so:

let myCar = new Car('red', 'sedan');

Inheritance

Inheritance is an OOP concept that allows you to create a new class from an existing class. The new class, known as the derived class, inherits the members of the class it is derived from, which is known as the base class. In Typescript, you can use the extends keyword to achieve inheritance.

class Tesla extends Car {
constructor(color: string, model: string, public autopilot: boolean) {
super(color, model);
}
}

Encapsulation

Encapsulation is another OOP concept that focuses on bundling data, and the methods that operate on that data, into a single unit. In Typescript, you can achieve encapsulation using the private and protected access modifiers.

class Car {
private speed: number;

constructor(public color: string, public model: string) {
this.speed = 0;
}

accelerate() {
this.speed += 10;
}
}

Polymorphism

Polymorphism is an OOP concept that allows a method to behave differently based on the object that it is acting upon. In Typescript, you can achieve polymorphism using methods and inheritance.

class Car {
constructor(public color: string, public model: string) {}

drive() {
console.log('Driving a car');
}
}

class Tesla extends Car {
drive() {
console.log('Driving a Tesla');
}
}

Conclusion

In conclusion, Object-Oriented Programming (OOP) in Typescript is a powerful way to structure your code in a way that is scalable, reusable, and easy to understand. By understanding the concepts of classes, inheritance, encapsulation, and polymorphism, you can start writing effective and efficient Typescript code. Happy coding!