Just Learn Code

Mastering Static and Abstract Classes in TypeScript

Static Class and Alternative

Have you ever heard of a static class in TypeScript? If you’re familiar with the Java programming language, this may be a term you’re already acquainted with.

A static class in TypeScript is like a sealed class in Java, which means it cannot be extended. In this article, we will explore the characteristics of static classes, their benefits, and explore alternatives that might be suitable for certain programming scenarios.

Definition of Static Class in TypeScript

A static class is a class that cannot be instantiated. In other words, you cannot create an object of a static class.

A static class is sealed, meaning that it cannot be extended or inherited. Why would you want to use a static class?

Well, they can be useful when you need to group related methods together, and it doesn’t make sense to create an instance of the class. An example of a static class in TypeScript might look like this:

“`

static class MathUtils {

static PI: number = 3.14159;

static calculateCircumference(diameter: number) {

return diameter * this.PI;

}

}

Let’s break this example down a bit.

The MathUtils class is defined as static, and the property PI is defined as a static property. This means that you can access PI without creating an instance of the MathUtils class.

Additionally, the calculateCircumference method is also defined as static, meaning you can access it without instantiating the MathUtils class.

Alternative to Static Class

While static classes can be useful, there are alternative options, such as top-level functions or objects. These alternatives can provide more flexibility in certain programming scenarios.

For example, consider a scenario where you’re working with a collection of utility functions that you need to group together. In this scenario, you might choose to define these functions as top-level functions in your module.

Here’s what that might look like:

“`

export function calculateCircumference(diameter: number) {

const PI = 3.14159;

return diameter * PI;

}

// Another utility function could be defined here… “`

Alternatively, you might choose to define these utility functions as properties on an object.

Here’s what that might look like:

“`

export const MathUtils = {

PI: 3.14159,

calculateCircumference(diameter: number) {

return diameter * this.PI;

},

// Another utility function could be defined here… };

“`

Overall, the decision to use a static class or an alternative approach will depend on the specific programming scenario you’re trying to solve.

When deciding on an approach, consider things like flexibility, ease of use, and organization.

Abstract Class in TypeScript

Abstract classes are another programming concept that you might encounter in TypeScript. An abstract class is a class that cannot be instantiated, much like a static class.

However, the purpose of an abstract class is typically different than that of a static class. Instead of grouping related methods together, an abstract class provides a base class from which other classes can inherit.

Definition of

Abstract Class in TypeScript

An abstract class is a class that provides a base implementation for other classes to inherit. Unlike a static class, which cannot be instantiated, an abstract class can be instantiated, but it’s typically not useful to do so.

The primary use case for an abstract class is to provide a base implementation that child classes can override and enhance. An example of an abstract class in TypeScript might look like this:

“`

abstract class Animal {

abstract makeNoise(): void;

move(distanceInMeters: number = 0) {

console.log(`Animal moved ${distanceInMeters}m.`);

}

}

“`

In this example, the Animal class is defined as abstract, and it provides an abstract method called makeNoise.

This means that any child class that inherits from Animal must provide its own implementation of the makeNoise method.

Abstract Methods and Properties in Abstract Class

An abstract class can contain both abstract methods and abstract properties. An abstract method is a method that is declared but has no implementation.

In other words, an abstract method is like a contract that child classes must fulfill. An abstract property is similar, but for properties instead of methods.

Here’s an example of an abstract class with both abstract properties and methods:

“`

abstract class Shape {

abstract getArea(): number;

// A readonly property can be defined as abstract

readonly numberOfSides: number;

constructor(numberOfSides: number) {

this.numberOfSides = numberOfSides;

}

}

class Square extends Shape {

// Implementation of getArea method is required

getArea(): number {

return this.sideLength ** 2;

}

constructor(public sideLength: number) {

super(4);

}

}

“`

In this example, the Shape class is defined as abstract, and it contains an abstract method called getArea as well as an abstract readonly property called numberOfSides. The Square class inherits from Shape and provides its own implementation of the getArea method.

Conclusion

In this article, we’ve explored two different programming concepts in TypeScript: static classes and abstract classes. We’ve defined what each of these concepts is and explored their benefits.

We’ve also discussed alternatives to static classes and how to use abstract methods and properties in an abstract class. By understanding these programming concepts, you’ll be better equipped to write cleaner, more organized code in TypeScript.

3) Example of Abstract Class Implementation

In the previous section, we discussed abstract classes and their benefits. In this section, we will explore a practical example of implementing an abstract class in TypeScript.

Abstract Class with Methods

Let’s say we’re building a web application that displays a list of users. We want to provide a common interface for retrieving and displaying user data.

To accomplish this, we can define an abstract class called UserService that defines a set of methods that child classes must override. “`

abstract class UserService {

abstract displayName(): void;

abstract find(id: number): void;

}

“`

In this example, the UserService class contains two abstract methods: displayName and find.

The displayName method is responsible for displaying the name of the user, while the find method is responsible for finding a user by their ID.

Implementation of Abstract Class in Child Class

Now, let’s create a child class called UserAjaxService that inherits from the abstract UserService class. The UserAjaxService class will implement the methods defined in the parent class.

“`

class UserAjaxService extends UserService {

constructor(private apiUrl: string) {

super();

}

displayName(): void {

// Implementation for displaying the name

}

find(id: number): void {

// AJAX request to find user by ID

}

}

“`

In this example, the UserAjaxService class performs an AJAX request to retrieve a user by ID. The constructor for the class accepts an API URL that is used to construct the request.

The displayName method is not shown, but it would be implemented to display the name of the user.

Creation of Object from Abstract Class

Now that we have a child class that implements the abstract methods from the UserService class, let’s create an object from the UserService class and see how the implementation works. “`

const userService: UserService = new UserAjaxService(‘http://localhost:3000/users’);

userService.find(1);

userService.displayName();

“`

In this example, we create a new UserAjaxService object and pass in the API URL as a constructor parameter.

We then call the find method with an ID of 1 to retrieve a user. Finally, we call the displayName method to display the name of the user.

Notice that we’re creating an object from the abstract UserService class, but the implementation is provided by the child class UserAjaxService.

4) Another Example of Abstract Class Implementation

In this section, we’ll explore another example of implementing an abstract class in TypeScript, this time with abstract properties.

Abstract Class with Properties

Let’s say we’re building an employee management system, and we need to define a common interface for employees. To accomplish this, we can define an abstract class called Employee that defines a set of properties that child classes must provide.

“`

abstract class Employee {

abstract name: string;

abstract empCode: number;

}

“`

In this example, the Employee class contains two abstract properties: name and empCode. The name property represents the name of the employee, while the empCode property represents their employee code.

Implementation of Abstract Properties in Child Class

Now, let’s create a child class called RegularEmployee that inherits from the abstract Employee class. The RegularEmployee class will provide the implementation for the abstract properties defined in the parent class.

“`

class RegularEmployee extends Employee {

constructor(public name: string, public empCode: number) {

super();

}

}

“`

In this example, the RegularEmployee class provides the implementation for the name and empCode properties, which are passed in as constructor parameters.

Object Creation and Display of Abstract Properties

Now that we have a child class that implements the abstract properties from the Employee class, let’s create an object from the Employee class and see how the implementation works. “`

const employee: Employee = new RegularEmployee(‘John Doe’, 12345);

console.log(employee.name);

“`

In this example, we create a new RegularEmployee object and pass in the name “John Doe” and the employee code 12345 as constructor parameters.

We then assign the object to a variable of type Employee. Finally, we log the value of the name property to the console.

Notice that we’re creating an object from the abstract Employee class, but the implementation is provided by the child class RegularEmployee.

Conclusion

In this article, we explored two practical examples of implementing abstract classes in TypeScript. We discussed abstract classes with methods and properties and explained how child classes inherit from and provide implementation for the abstract methods and properties defined in the parent class.

By understanding these programming concepts, you’ll be better equipped to write cleaner, more organized code in TypeScript. In this article, we delved into the concepts of static and abstract classes in TypeScript, and their implementation in child classes.

We started by discussing what these concepts entail, and explored how they can be useful in certain programming scenarios. We then provided practical examples of implementing both concrete and abstract classes in child classes, and demonstrated how these concepts can lead to cleaner and more organized code.

With the knowledge gained from this article, readers will be better equipped to understand and apply these concepts in their future TypeScript projects, resulting in more efficient and effective programming. Ultimately, by mastering these concepts, programmers will be able to write more complex code with ease and maintainability, setting them up for success in their programming endeavors.

Popular Posts