Site icon DataFlair

TypeScript Classes

typescript classes

We offer you a brighter future with industry-ready online courses - Start Now!!

Classes are a crucial feature of object-oriented programming (OOP). It allows developers to create reusable code by grouping related data and functions into a class unit. In TypeScript, classes are used to define the structure of an object, its properties, and its methods.

Creating a Class in TypeScript

To create a class in TypeScript, we use the keyword ‘class’ followed by the name of the class. Look at the following syntax:

class DataFlairMyClass {
 // class properties and methods
}

Defining Properties in a Class

Properties are used to store data in a class. We use the ‘constructor’ method to define properties in a class. The constructor method is a unique method called when an object of the class is created. We can define properties by adding parameters to the constructor method and assigning them to class properties. Here is an example:

class DataFlair_Person {
 firstName: string;
 lastName: string;


 constructor(firstName: string, lastName: string) {
   this.firstName = firstName;
   this.lastName = lastName;
 }
}

In this example, we have defined a class called ‘DataFlair_Person’ with two properties: firstName and lastName. We have defined a constructor method with two parameters: firstName and lastName. The ‘this’ keyword is used to refer to the properties of the class.

Defining Methods in a Class

Methods are used to perform actions in a class. To define methods in a class, we add them inside the class. Here is an example:

class DataFlair_Person {
 firstName: string;
 lastName: string;


 constructor(firstName: string, lastName: string) {
   this.firstName = firstName;
   this.lastName = lastName;
 }


 getFullName(): string {
   return `${this.firstName} ${this.lastName}`;
 }
}

In this example, we have added a method called ‘getFullName’ to the ‘DataFlair_Person’ class. The method returns the person’s full name by combining the firstName and lastName properties.

Access Modifiers in TypeScript

Access modifiers are used to control the visibility of class properties and methods. TypeScript provides three access modifiers: public, private, and protected.

1. Public Access Modifier:

This is the default access modifier. Public properties and methods can be accessed from anywhere, including outside the class.

2. Private Access Modifier:

Private properties and methods can only be accessed within the class. Inaccessible to outsiders are private properties and practices.

3. Protected Access Modifier:

Protected properties and methods can be accessed within the class and its subclasses. These cannot be accessed outside the class or its subclasses.

Here is an example:

class DataFlair_Person {
 private age: number;

 constructor(age: number) {
   this.age = age;
 }

 getAge(): number {
   return this.age;
 }
}

class Employee extends DataFlair_Person {
 private salary: number;

 constructor(age: number, salary: number) {
   super(age);
   this.salary = salary;
 }

 getSalary(): number {
   return this.salary;
 }
}

In this example, we have defined a class called ‘Person’ with a private property called ‘age’ and a method called ‘getAge’ that returns the age. We have also defined a subclass called ‘Employee’ that extends the ‘Person’ class. The ‘Employee’ class has a private property called ‘salary’ and a method called ‘getSalary’ that returns the salary.

Inheritance in TypeScript

Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a class to inherit properties and methods from another class. In TypeScript, inheritance is achieved using the “extends” keyword.

When a class “extends” another class, it inherits all of the properties and methods of the base class. The derived class can then add its properties and methods or override those of the base class if needed. This is called “subclassing” or “deriving” from the base class.

Here is an example of inheritance in TypeScript:

class DataFlair_Animal {
 name: string;

 constructor(name: string) {
   this.name = name;
 }

 move(distanceInMeters: number = 0) {
   console.log(`${this.name} moved ${distanceInMeters}m.`);
 }
}

class Dog extends DataFlair_Animal {
 bark() {
   console.log('Woof! Woof!');
 }
}

const dog = new Dog('Rufus');
dog.bark(); 
dog.move(10); 

Output

Woof! Woof!
Rufus moved 10m.

In this example, the “Dog” class extends the “DataFlair_Animal” class and inherits the “name” and “move” properties and methods. The “Dog” class also has its method, “bark,” which is not present in the “DataFair_Animal” class.

Overall, inheritance allows for code reuse and promotes a more organized and efficient codebase.

Accessors in TypeScript

Accessors, or getters and setters, are a type of method in TypeScript and other object-oriented programming languages that allow controlled access to an object’s properties. TypeScript defines accessors using the “get” and “set” keywords.

Getters are used to retrieve the value of a property, while setters are used to set the value of a property. Using accessors, developers can implement additional logic to control how the property is accessed and modified.

Here is an example of accessors in TypeScript:

class DataFlair_Person {
 private _age: number;

 get age(): number {
   return this._age;
 }

 set age(newAge: number) {
   if (newAge >= 0 && newAge <= 120) {
     this._age = newAge;
   } else {
     console.log('Invalid age.');
   }
 }
}

const person = new DataFlair_Person();
person.age = 25;
console.log(person.age); // 
person.age = 150; // 

Output

25
Invalid age.

In this example, the “DataFlair_Person” class has a private property “_age” and public accessors “get age()” and “set age(newAge: number).” The “set age()” accessor checks if the new age value is valid before setting the value of the private property. An error message is printed on the console if the new age is invalid.

Overall, accessors provide a convenient way to encapsulate data and control access to it, which can help improve code quality and maintainability.

Static Properties of Class in TypeScript

Static properties are class property in TypeScript that belong to the class itself rather than to class instances. They are defined using the “static” keyword and are accessed using the class name rather than an instance of the class.

Static properties can be useful for storing data or functionality shared across all instances of a class, such as a counter or a utility function.

Here is an example of a static property in TypeScript:

class DataFlair_Person {
 static MAX_AGE = 120;


 name: string;
 age: number;


 constructor(name: string, age: number) {
   this.name = name;
   this.age = age;
 }


 static isValidAge(age: number): boolean {
   return age >= 0 && age <= DataFlair_Person.MAX_AGE;
 }
}


const person1 = new DataFlair_Person('Alice', 25);
const person2 = new DataFlair_Person('Bob', 150);


console.log(DataFlair_Person.MAX_AGE); 
console.log(DataFlair_Person.isValidAge(25));
console.log(DataFlair_Person.isValidAge(150));

Output

120
true
false

In this example, the “DataFlair_Person” class has a static property “MAX_AGE” and a static method “isValidAge”. The “MAX_AGE” property is accessed using the class name “DataFlair_Person,” while the “isValidAge” method is also accessed using the class name and takes an age parameter to check if it is valid.

Static properties can be useful for organizing and sharing data and functionality across a class, especially in scenarios where the data or functionality should not belong to any particular class instance.

Abstract Classes in TypeScript

Abstract classes are a type of class in TypeScript that cannot be instantiated directly but instead serve as a blueprint or template for other classes. They are defined using the “abstract” keyword and can contain concrete and abstract methods and properties.

Abstract classes provide a way to define a common set of properties and methods that a group of related classes can inherit from. They can also provide default behavior and enforce certain constraints on the classes that inherit from them.

Here is an example of an abstract class in TypeScript:

abstract class DataFlair_Shape {
 abstract getArea(): number;
}

class Rectangle extends DataFlair_Shape {
 private width: number;
 private height: number;

 constructor(width: number, height: number) {
   super();
   this.width = width;
   this.height = height;
 }

 getArea(): number {
   return this.width * this.height;
 }
}

class Circle extends DataFlair_Shape {
 private radius: number;

 constructor(radius: number) {
   super();
   this.radius = radius;
 }

 getArea(): number {
   return Math.PI * this.radius ** 2;
 }
}

const rectangle = new Rectangle(10, 5);
console.log(rectangle.getArea());

const circle = new Circle(5);
console.log(circle.getArea()); 

Output

50
78.53981633974483

In this example, the “DataFlair_Shape” class is an abstract class that defines an abstract method “getArea().” The “Rectangle” and “Circle” classes inherit from the “DataFlair_Shape” class and implement the “getArea()” method according to their respective shapes.

Abstract classes can be a powerful tool for designing flexible and extensible code by providing a common interface for related classes while allowing each class to define its behavior.

Constructor in TypeScript

A constructor is a special method in TypeScript called when a class object is created. It initializes the object’s properties and performs any necessary setup or validation.

TypeScript defines a constructor using the “constructor” keyword and can take zero or more parameters. The constructor is automatically called when an object is created using the “new” keyword.

Here is an example of a constructor in TypeScript:

class DataFlair_Person {
 name: string;
 age: number;


 constructor(name: string, age: number) {
   this.name = name;
   this.age = age;
 }
}


const person = new DataFlair_Person('Alice', 25);
console.log(person.name); 
console.log(person.age); 

Output

Alice
25

In this example, the “DataFlair_Person” class has a constructor that takes two parameters, “name” and “age.” The constructor initializes the object’s “name” and “age” properties using the values of the parameters.

Constructors can also perform other setup tasks, such as initializing other objects or connecting to a database. Constructors can also be overloaded by defining multiple constructor methods with different parameter types or numbers.

Overall, constructors provide a way to initialize objects and perform necessary setup tasks, making them a fundamental part of object-oriented programming in TypeScript.

Overloading in TypeScript

Overloading is a feature in TypeScript that allows a function or method to have multiple signatures with different parameter types or numbers. This can provide more flexibility and convenience for calling the function or method.

Overloading is useful when a function or method can take different types or numbers of parameters but still has the same logical behavior. Instead of defining separate functions or methods for each variation, overloading allows them to be combined into a single function or method with multiple signatures.

Here is an example of overloading in TypeScript:

function DataFlair_add(a: number, b: number): number;
function DataFlair_add(a: string, b: string): string;
function DataFlair_add(a: any, b: any): any {
 return a + b;
}


console.log(DataFlair_add(1, 2));
console.log(DataFlair_add('Hello', 'World'));

Output

3
HelloWorld

In this example, the “DataFlair_add” function is overloaded with two signatures: one that takes two numbers and returns a number and one that takes two strings and returns a string. The actual implementation of the function is a single method that takes any type of parameter and returns any type of result. The implementation uses the same logical behavior of concatenating the parameters for both number and string inputs.

Overloading is also commonly used in object-oriented programming to provide multiple constructors with different parameter types or numbers or multiple methods with different parameters but the same name.

Overloading is a powerful tool for creating flexible and reusable functions or methods in TypeScript, allowing developers to define multiple logical variations of the same function or method with a single implementation.

Conclusion

Classes are a powerful feature of TypeScript that allows developers to organize their code in a more structured and maintainable way. By defining classes with properties and methods, developers can create reusable code and avoid duplicating code in multiple places. TypeScript’s support for access modifiers also allows developers to control the visibility of class members, making it easier to write secure and maintainable code.

In addition to classes, TypeScript provides other features that make it a powerful language for building complex applications, including interfaces, generics, and modules. These features make writing scalable and maintainable code easier, especially in large projects with many contributors.

Overall, classes are an essential part of TypeScript and OOP. They provide a way to structure code and create reusable components, essential in modern software development. Whether working on a small project or an extensive enterprise application, TypeScript’s classes can help you write better, more maintainable code.

Exit mobile version