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
Animal
with a propertycolor
and a methodwalk()
. -
The constructor is used to initialize the class with a value for
color
. -
We created an instance of the
Animal
class and called itswalk
method.
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
Animals
class has two properties:size
andcolor
. -
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,
animal1
andanimal2
, 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
Dog
class extends theAnimal
class and inherits thename
property. -
The
speak
method is overridden in theDog
class 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
OnlineTraining
class overrides theteach
method from theTraining
class. -
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
companyName
property 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
sname
property ispublic
, so it can be accessed outside the class. -
The
roll
property isprivate
, so it can only be accessed within thePrivateData
class.
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
Car
with 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
Laptop
with 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
Book
with 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
Mobile
withmodel
andprice
properties. -
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
Vehicle
with a propertyname
and a methodmove()
. -
Create a child class
Bike
that extendsVehicle
. -
Override the
move()
method inBike
to print a different message. -
Create an object of
Bike
and call themove()
method.
Assignment 6: Practice Method Overriding
-
Create a parent class
Account
with a methodgetAccountType()
that prints"Generic Account"
. -
Create a subclass
SavingAccount
that overridesgetAccountType()
to print"Saving Account"
. -
Create an object of
SavingAccount
and callgetAccountType()
.
Assignment 7: Static Members
-
Create a class
University
with 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
Student
with:-
public
propertyname
-
private
propertyid
-
-
Create a method
displayStudent()
inside the class that prints bothname
andid
. -
Create an object of
Student
and calldisplayStudent()
.
Assignment 9: Protected Access Specifier
-
Create a class
Employee
with aprotected
propertyemployeeId
. -
Create a subclass
Manager
that inheritsEmployee
. -
Inside
Manager
, create a methodshowEmployeeId()
that printsemployeeId
. -
Create an object of
Manager
and callshowEmployeeId()
.
Assignment 10: Real-Life Mini Project (Combination of All Topics)
-
Create a class
Person
withname
,age
, and a methodintroduce()
. -
Create a subclass
Teacher
that extendsPerson
and adds a propertysubject
. -
Override the
introduce()
method inTeacher
to include the subject. -
Add a static property
schoolName
and static methodgetSchoolName()
. -
Create objects of
Person
andTeacher
. -
Access the static method directly from the class.