TypeScript Classes and Objects
Classes are the core concept of object-oriented programming (OOP), serving as blueprints for creating objects. TypeScript fully supports the class syntax introduced in ES6 and adds features like type annotations and access modifiers on top of it.
What are Classes and Objects?
- Class: A template or blueprint used to describe the common properties (data) and behaviors (methods) of a category of objects.
- Object: An instance of a class. Created using the
newkeyword, possessing the properties and methods defined by the class.
Defining a Class
Here's a simple class definition:
Inheritance
Inheritance is a mechanism that allows one class (subclass) to acquire the properties and methods of another class (parent class). Use the extends keyword to implement inheritance.
super(): In a subclass constructor, you must callsuper()to execute the parent class constructor.super.method(): Can be used to call overridden methods from the parent class.
Access Modifiers
TypeScript provides three access modifiers to control the accessibility of class members (properties and methods).
-
public(default): Members can be accessed anywhere. If you don't specify a modifier, it defaults topublic. -
private: Members can only be accessed within the class where they're declared. Neither subclasses nor class instances can access them. -
protected: Members can be accessed within the class where they're declared and in subclasses of that class, but not on class instances.
Readonly Modifier (readonly)
The readonly keyword ensures that a property can only be initialized when declared or in the constructor, and cannot be modified afterward.
Static Properties and Methods (static)
Static members belong to the class itself, not to instances of the class. You can access them directly through the class name without creating an object.
Abstract Classes (abstract)
Abstract classes serve as base classes for other classes. They cannot be directly instantiated. Abstract classes can contain abstract methods, which have no concrete implementation and must be implemented in derived classes.