Working with Class Types in TypeScript
Working with Class Types in TypeScript
TypeScript provides a class type which makes it easy to create different types of classes. In this article, we will look at how to use class types in TypeScript.
Defining Classes
Defining classes in TypeScript is straightforward and follows the same syntax as other object-oriented languages such as Java and C#. Here is an example of a basic class definition in TypeScript:
class MyClass {
// Properties
public name: string;
public age: number;
// Constructor
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
This is a basic class definition, but it already contains all the features that are needed to create more advanced classes. Let's take a look at each part of the class.
Properties
Properties are the variables that make up an instance of a class. In our example, we have two properties, name and age. They are both declared with the public keyword which means that they will be accessible from outside the class.
Constructor
The constructor is a special function that is used to initialize the class. In our example, we have a simple constructor that takes two arguments (name and age) and assigns them to the corresponding properties. Note that the constructor must have the same name as the class.
Using Classes
Once a class has been defined, it can be used to create instances of that class. This is done using the new keyword followed by the class name. For example:
let myInstance = new MyClass("John", 25);
This creates an instance of the MyClass class and assigns it to the myInstance variable. The constructor is automatically called and the given values are assigned to the corresponding properties.
The properties of the class can then be accessed using the dot notation:
let name = myInstance.name; // "John"
let age = myInstance.age; // 25
Class Inheritance
Classes can also be extended to form new classes. This is known as inheritance. For example, if we want to create a new class which extends from MyClass, we can use the extends keyword:
class MyNewClass extends MyClass {
// ...
}
This creates a new class, MyNewClass, which inherits all the properties and methods of MyClass. This makes it much easier to reuse existing code and to create complex class hierarchies.
Conclusion
Class types can make it easier to create and maintain complex object-oriented applications in TypeScript. By understanding how to define classes, use them, and extend them via inheritance, you will be able to create powerful and re-usable classes for your application.