Class
Class Common Syntax
The class
keyword is used in TypeScript to define a class. Below, you can see an example:
The class
keyword is used to define a class named “Person”.
The class has two private properties: name of type string
and age of type number
.
The constructor is defined using the constructor
keyword. It takes name and age as parameters and assigns them to the corresponding properties.
The class has a public
method named sayHi that logs a greeting message.
To create an instance of a class in TypeScript, you can use the new
keyword followed by the class name, followed by parentheses ()
. For instance:
Constructor
Constructors are special methods within a class that are used to initialize the object’s properties when an instance of the class is created.
It is possible to overload a constructor using the following syntax:
In TypeScript, it is possible to define multiple constructor overloads, but you can have only one implementation that must be compatible with all the overloads, this can be achieved by using an optional parameter.
Private and Protected Constructors
In TypeScript, constructors can be marked as private or protected, which restricts their accessibility and usage.
Private Constructors: Can be called only within the class itself. Private constructors are often used in scenarios where you want to enforce a singleton pattern or restrict the creation of instances to a factory method within the class
Protected Constructors: Protected constructors are useful when you want to create a base class that should not be instantiated directly but can be extended by subclasses.
Access Modifiers
Access Modifiers private
, protected
, and public
are used to control the visibility and accessibility of class members, such as properties and methods, in TypeScript classes. These modifiers are essential for enforcing encapsulation and establishing boundaries for accessing and modifying the internal state of a class.
The private
modifier restricts access to the class member only within the containing class.
The protected
modifier allows access to the class member within the containing class and its derived classes.
The public
modifier provides unrestricted access to the class member, allowing it to be accessed from anywhere.”
Get and Set
Getters and setters are special methods that allow you to define custom access and modification behavior for class properties. They enable you to encapsulate the internal state of an object and provide additional logic when getting or setting the values of properties.
In TypeScript, getters and setters are defined using the get
and set
keywords respectively. Here’s an example:
Auto-Accessors in Classes
TypeScript version 4.9 adds support for auto-accessors, a forthcoming ECMAScript feature. They resemble class properties but are declared with the “accessor” keyword.
Auto-accessors are “de-sugared” into private get
and set
accessors, operating on an inaccessible property.
this
In TypeScript, the this
keyword refers to the current instance of a class within its methods or constructors. It allows you to access and modify the properties and methods of the class from within its own scope.
It provides a way to access and manipulate the internal state of an object within its own methods.
Parameter Properties
Parameter properties allow you to declare and initialize class properties directly within the constructor parameters avoiding boilerplate code, example:
Abstract Classes
Abstract Classes are used in TypeScript mainly for inheritance, they provide a way to define common properties and methods that can be inherited by subclasses. This is useful when you want to define common behavior and enforce that subclasses implement certain methods. They provide a way to create a hierarchy of classes where the abstract base class provides a shared interface and common functionality for the subclasses.
With Generics
Classes with generics allow you to define reusable classes which can work with different types.
Decorators
Decorators provide a mechanism to add metadata, modify behavior, validate, or extend the functionality of the target element. They are functions that execute at runtime. Multiple decorators can be applied to a declaration.
Decorators are experimental features, and the following examples are only compatible with TypeScript version 5 or above using ES6.
For TypeScript versions prior to 5, they should be enabled using the experimentalDecorators
property in your tsconfig.json
or by using --experimentalDecorators
in your command line (but the following example won’t work).
Some of the common use cases for decorators include:
- Watching property changes.
- Watching method calls.
- Adding extra properties or methods.
- Runtime validation.
- Automatic serialization and deserialization.
- Logging.
- Authorization and authentication.
- Error guarding.
Note: Decorators for version 5 do not allow decorating parameters.
Types of decorators:
Class Decorators
Class Decorators are useful for extending an existing class, such as adding properties or methods, or collecting instances of a class. In the following example, we add a toString
method that converts the class into a string representation.
Property Decorator
Property decorators are useful for modifying the behavior of a property, such as changing the initialization values. In the following code, we have a script that sets a property to always be in uppercase:
Method Decorator
Method decorators allow you to change or enhance the behavior of methods. Below is an example of a simple logger:
It logs:
Getter and Setter Decorators
Getter and setter decorators allow you to change or enhance the behavior of class accessors. They are useful, for instance, for validating property assignments. Here’s a simple example for a getter decorator:
Decorator Metadata
Decorator Metadata simplifies the process for decorators to apply and utilize metadata in any class. They can access a new metadata property on the context object, which can serve as a key for both primitives and objects.
Metadata information can be accessed on the class via Symbol.metadata
.
Metadata can be used for various purposes, such as debugging, serialization, or dependency injection with decorators.
Inheritance
Inheritance refers to the mechanism by which a class can inherit properties and methods from another class, known as the base class or superclass. The derived class, also called the child class or subclass, can extend and specialize the functionality of the base class by adding new properties and methods or overriding existing ones.
TypeScript does not support multiple inheritance in the traditional sense and instead allows inheritance from a single base class. TypeScript supports multiple interfaces. An interface can define a contract for the structure of an object, and a class can implement multiple interfaces. This allows a class to inherit behavior and structure from multiple sources.
The class
keyword in TypeScript, similar to JavaScript, is often referred to as syntactic sugar. It was introduced in ECMAScript 2015 (ES6) to offer a more familiar syntax for creating and working with objects in a class-based manner. However, it’s important to note that TypeScript, being a superset of JavaScript, ultimately compiles down to JavaScript, which remains prototype-based at its core.
Statics
TypeScript has static members. To access the static members of a class, you can use the class name followed by a dot, without the need to create an object.
Property initialization
There are several ways how you can initialize properties for a class in TypeScript:
Inline:
In the following example these initial values will be used when an instance of the class is created.
In the constructor:
Using constructor parameters:
Method overloading
Method overloading allows a class to have multiple methods with the same name but different parameter types or a different number of parameters. This allows us to call a method in different ways based on the arguments passed.