TypeScript, being a superset of JavaScript, brings additional features to the language that make it more robust and easier to maintain. One such feature is the support for object-oriented programming (OOP) through classes. In this tutorial, we will explore how to define and use classes in TypeScript, including constructors, methods, and properties.
In TypeScript, a class is a blueprint for creating objects. It encapsulates data for the object and methods to manipulate that data. Classes in TypeScript are similar to those in other object-oriented languages like Java or C#. They provide a way to organize your code into logical groups of variables and functions.
class keyword.Let's start by looking at some practical examples to understand how classes work in TypeScript.
Here is a simple example of a class that represents a Car.
1class Car {2// Properties3make: string;4model: string;5year: number;67// Constructor8constructor(make: string, model: string, year: number) {9this.make = make;10this.model = model;11this.year = year;12}1314// Method15displayInfo(): void {16console.log(`Car: ${this.make} ${this.model}, Year: ${this.year}`);17}18}1920// Creating an instance of the Car class21const myCar = new Car('Toyota', 'Corolla', 2021);22myCar.displayInfo();
$ ts-node car.ts
Car: Toyota Corolla, Year: 2021
In this example:
Car class with properties make, model, and year.displayInfo method logs the car's information to the console.TypeScript supports inheritance, allowing you to create a new class based on an existing one. This is useful for reusing code and creating more specialized classes.
1class ElectricCar extends Car {2batteryCapacity: number;34constructor(make: string, model: string, year: number, batteryCapacity: number) {5super(make, model, year);6this.batteryCapacity = batteryCapacity;7}89displayBatteryInfo(): void {10console.log(`Battery Capacity: ${this.batteryCapacity} kWh`);11}12}1314const myElectricCar = new ElectricCar('Tesla', 'Model S', 2022, 100);15myElectricCar.displayInfo();16myElectricCar.displayBatteryInfo();
$ ts-node electric-car.ts
Car: Tesla Model S, Year: 2022 Battery Capacity: 100 kWh
In this example:
ElectricCar class that extends the Car class.super() to initialize the properties from the parent class (Car).batteryCapacity and a method displayBatteryInfo.In the next section, we will explore Access Modifiers in TypeScript. Access modifiers control the visibility of class members (properties and methods) and help in encapsulating data.
Stay tuned for more advanced topics in TypeScript!