Classes and Objects in TypeScript - A Fundamental Concept


Introduction

Classes and objects are fundamental concepts in Object-Oriented Programming (OOP). TypeScript, as an OOP language, allows you to define and work with classes and create objects from those classes. In this guide, we'll explore how classes and objects are used in TypeScript.


Defining a Class

A class is a blueprint for creating objects. It defines the structure and behavior of objects of that class.


Example:

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

Creating Objects

Objects are instances of classes. You can create objects using the new keyword.


Example:

const john = new Person("John", "Doe");
const alice = new Person("Alice", "Smith");

Accessing Properties and Methods

You can access the properties and methods of an object using the dot notation.


Example:

console.log(john.firstName); // "John"
console.log(alice.getFullName()); // "Alice Smith"

Constructors and Initialization

The constructor is a special method that gets called when an object is created from a class. It is used to initialize object properties.


Example:

class Product {
name: string;
price: number;
constructor(name: string, price: number) {
this.name = name;
this.price = price;
}
}
const laptop = new Product("Laptop", 899);

Class Methods

Classes can have methods that define behaviors associated with objects of that class.


Example:

class Circle {
radius: number;
constructor(radius: number) {
this.radius = radius;
}
getArea() {
return Math.PI * this.radius * this.radius;
}
}
const myCircle = new Circle(5);
const area = myCircle.getArea();

Conclusion

Classes and objects are fundamental building blocks in TypeScript and Object-Oriented Programming. They allow you to structure and organize your code, model real-world entities, and define their behavior. As you continue your TypeScript journey, explore more advanced OOP concepts like inheritance, encapsulation, and polymorphism to create robust and maintainable applications.