Understanding Classes and Objects in TypeScript
TypeScript, being a superset of JavaScript, enhances JavaScript by introducing support for object-oriented programming (OOP) features like classes, objects, inheritance, and polymorphism. While JavaScript doesn’t support OOP directly, TypeScript makes it easier to work with objects and classes by providing the tools necessary for object-oriented design. This chapter will cover everything you need to know about classes, objects, and their various features in TypeScript.
If you’re coming from an object-oriented background in languages like Java, C++, or C#, you’ll find this chapter easy to understand. However, if you’re new to OOP, make sure to pay attention and follow along with the examples!
What is a Class?
A class in TypeScript is a blueprint for creating objects with shared properties and methods. It defines the common behavior and attributes that its objects (instances) will have. A class encapsulates data and behavior into one structure.
What is an Object?
An object is an instance of a class. Once a class is defined, you can create multiple objects (instances) from that class. Each object will have the same properties and methods as the class but with different values.
Creating Classes in TypeScript
To define a class in TypeScript, you use the class keyword, followed by the class name, and curly braces {} to define the properties and methods of the class.
Syntax for Creating a Class:
Naming Conventions for Classes:
-
Class names should be written in PascalCase (e.g.,
Animal). -
Class names cannot start with a number, contain special characters, or have spaces.
Example 1: Basic Class in TypeScript
Here is a simple example of a class with properties and a method:
Explanation:
-
We have created a class
Animalwith a propertycolorand a methodwalk(). -
The constructor is used to initialize the class with a value for
color. -
We created an instance of the
Animalclass and called itswalkmethod.
Output:
Creating Instance Objects
To create an instance of a class and access its properties or methods, you use the new keyword.
Syntax:
In the above example, we created an instance of the Animal class using the new keyword and passed an argument "White" to the constructor.
Example 2: More Complex Class with Properties and Methods
Let’s expand on the previous example with multiple properties and methods:
Explanation:
-
The
Animalsclass has two properties:sizeandcolor. -
The constructor allows you to initialize these properties when creating an object. Default values are provided if no values are passed.
-
We create two objects,
animal1andanimal2, each with different values.
Output:
Class Inheritance
TypeScript supports inheritance, where one class (child class) can inherit properties and methods from another class (parent class). The extends keyword is used for inheritance.
Example 3: Inheritance in TypeScript
Explanation:
-
The
Dogclass extends theAnimalclass and inherits thenameproperty. -
The
speakmethod is overridden in theDogclass to provide a more specific implementation.
Output:
Method Overriding
Method overriding allows a subclass to provide its own implementation of a method that is already defined in the parent class.
Example 4: Method Overriding
Explanation:
-
The
OnlineTrainingclass overrides theteachmethod from theTrainingclass. -
The
super.teach()inside the child class calls the method from the parent class before adding its own behavior.
Output:
Static Members
Static members belong to the class itself rather than to instances of the class. They are accessed directly using the class name, without needing to create an instance.
Example 5: Static Members in a Class
Explanation:
-
The
companyNameproperty is static, so it belongs to the class, not to an individual instance. -
We access the static property directly using the class name
Employee.
🔐 Access Specifiers in TypeScript (with WiFi Example)
Access specifiers determine how class members are visible to other parts of your code. TypeScript supports three access modifiers:
-
public: Accessible from anywhere – like Airport WiFi -
protected: Accessible within the class and its subclasses – like Office WiFi (only for employees) -
private: Accessible only within the class – like Personal Mobile Hotspot
Access Specifiers
class WiFiAccess {
public airportWiFi: string = "Open WiFi - Everyone can connect";
protected officeWiFi: string = "Office WiFi - Employees only";
private personalHotspot: string = "Private Hotspot - Only I can access";
showAccess(): void {
console.log("Public:", this.airportWiFi);
console.log("Protected:", this.officeWiFi);
console.log("Private:", this.personalHotspot);
}
}
class OfficeUser extends WiFiAccess {
accessWiFi(): void {
console.log("Accessing:", this.airportWiFi); // ✅ Public
console.log("Accessing:", this.officeWiFi); // ✅ Protected
// console.log(this.personalHotspot); // ❌ Error: private
}
}
const user = new WiFiAccess();
console.log(user.airportWiFi); // ✅ Public
// console.log(user.officeWiFi); // ❌ Error: protected
// console.log(user.personalHotspot); // ❌ Error: private
user.showAccess(); // ✅ Can access all within the class
Explanation:
-
The
snameproperty ispublic, so it can be accessed outside the class. -
The
rollproperty isprivate, so it can only be accessed within thePrivateDataclass.
Conclusion
In this chapter, we’ve covered the basics of classes and objects in TypeScript, including:
-
Class Declaration: Creating classes with properties, methods, and constructors.
-
Object Creation: Instantiating objects from classes and accessing their members.
-
Inheritance: Extending a class to create subclasses.
-
Method Overriding: Overriding methods from parent classes in child classes.
-
Static Members: Using static members that belong to the class itself.
-
Access Specifiers: Controlling the visibility of class members with
public,private, andprotected.
Assignment 1: Create a Basic Class
-
Create a class
Carwith a single propertybrand(string). -
Create a constructor to initialize
brand. -
Add a method
displayBrand()to print the brand. -
Create an object of the class and call the method.
Assignment 2: Add Multiple Properties
-
Create a class
Laptopwith properties:brand(string) andprice(number). -
Create a constructor to initialize both properties.
-
Add a method
displayInfo()to display brand and price. -
Create two different objects with different values and call the method on each.
Assignment 3: Use Default Values in Constructor
-
Create a class
Bookwith properties:title(string) andauthor(string). -
Set default values for both properties inside the constructor.
-
Allow passing custom values as well when creating objects.
-
Create two objects: one with default values, one with custom values.
Assignment 4: Create Objects Dynamically
-
Create a class
Mobilewithmodelandpriceproperties. -
Create a constructor to initialize these properties.
-
Create five different objects dynamically with different models and prices.
-
Display their information using a method.
Assignment 5: Inheritance (Extending a Class)
-
Create a parent class
Vehiclewith a propertynameand a methodmove(). -
Create a child class
Bikethat extendsVehicle. -
Override the
move()method inBiketo print a different message. -
Create an object of
Bikeand call themove()method.
Assignment 6: Practice Method Overriding
-
Create a parent class
Accountwith a methodgetAccountType()that prints"Generic Account". -
Create a subclass
SavingAccountthat overridesgetAccountType()to print"Saving Account". -
Create an object of
SavingAccountand callgetAccountType().
Assignment 7: Static Members
-
Create a class
Universitywith a static propertyuniversityName. -
Create a static method
getUniversityName(). -
Access and print the static property without creating an instance.
Assignment 8: Access Specifiers
-
Create a class
Studentwith:-
publicpropertyname -
privatepropertyid
-
-
Create a method
displayStudent()inside the class that prints bothnameandid. -
Create an object of
Studentand calldisplayStudent().
Assignment 9: Protected Access Specifier
-
Create a class
Employeewith aprotectedpropertyemployeeId. -
Create a subclass
Managerthat inheritsEmployee. -
Inside
Manager, create a methodshowEmployeeId()that printsemployeeId. -
Create an object of
Managerand callshowEmployeeId().
Assignment 10: Real-Life Mini Project (Combination of All Topics)
-
Create a class
Personwithname,age, and a methodintroduce(). -
Create a subclass
Teacherthat extendsPersonand adds a propertysubject. -
Override the
introduce()method inTeacherto include the subject. -
Add a static property
schoolNameand static methodgetSchoolName(). -
Create objects of
PersonandTeacher. -
Access the static method directly from the class.
