TypeScript extends JavaScript by introducing strong typing and object-oriented programming concepts. One of the most important features in this paradigm is the class. Classes allow you to create blueprints for objects and define their properties and behaviors in a structured manner. Let's dive into the world of TypeScript classes!
Basic Syntax of Classes
At its core, a class in TypeScript is defined using the class
keyword, followed by the class name. The body of the class contains the properties and methods.
class Animal { name: string; constructor(name: string) { this.name = name; } speak(): void { console.log(`${this.name} makes a noise.`); } }
Breakdown of the Example
- Class Declaration: The
class Animal
defines a new class calledAnimal
. - Properties: We declare a property
name
of typestring
. - Constructor: The
constructor
method is a special function that gets called when a new instance of the class is created. - Methods: The
speak
method outputs a message to the console.
Creating Instances
We can create an instance of the Animal
class using the new
keyword:
const dog = new Animal("Buddy"); dog.speak(); // Output: Buddy makes a noise.
Inheritance in Classes
One of the major advantages of using classes is inheritance. This allows one class to derive properties and methods from another class.
Example of Inheritance
class Dog extends Animal { speak(): void { console.log(`${this.name} barks.`); } } const dog = new Dog("Buddy"); dog.speak(); // Output: Buddy barks.
Breakdown of Inheritance
- Extending Classes: The
Dog
class extends theAnimal
class, meaning it inherits all of its properties and methods. - Overriding Methods: The
speak
method in theDog
class overrides the same method inAnimal
, providing a specific implementation for dogs.
Access Modifiers
TypeScript also provides access modifiers that define the visibility of class members. The three main access modifiers are public
, private
, and protected
.
Example with Access Modifiers
class Person { public name: string; private age: number; // Only accessible within this class protected species: string; // Accessible within this class and subclasses constructor(name: string, age: number, species: string) { this.name = name; this.age = age; this.species = species; } } const john = new Person("John", 30, "Homo Sapiens"); console.log(john.name); // Output: John // console.log(john.age); // Error: Property 'age' is private and only accessible within class 'Person'
Understanding Access Modifiers
- Public: Members are accessible from anywhere.
- Private: Members are only accessible within the class.
- Protected: Members are accessible within the class and subclasses.
Static Methods and Properties
Static properties and methods belong to the class itself rather than instances of the class. They are useful for utility functions or constants.
Creating Static Members
class MathUtils { static PI: number = 3.14; static calculateCircumference(radius: number): number { return 2 * MathUtils.PI * radius; } } console.log(MathUtils.PI); // Output: 3.14 console.log(MathUtils.calculateCircumference(5)); // Output: 31.400000000000002
Breakdown of Static Members
- Static Properties:
PI
is a static property accessible using the class name. - Static Methods:
calculateCircumference
can be called without creating an instance ofMathUtils
.
Abstract Classes
Abstract classes cannot be instantiated directly and are designed to be extended by other classes. This is useful for defining base classes for other derived classes.
Example of Abstract Classes
abstract class Shape { abstract getArea(): number; // Abstract method printArea(): void { console.log(`Area: ${this.getArea()}`); } } class Circle extends Shape { private radius: number; constructor(radius: number) { super(); this.radius = radius; } getArea(): number { return Math.PI * this.radius * this.radius; } }
Understanding Abstract Classes
- Abstract Classes: The
Shape
class contains an abstract methodgetArea
, which must be implemented by derived classes. - Derived Class: The
Circle
class implements thegetArea
method, providing a specific implementation.
By leveraging the power of classes in TypeScript, you can build clean, well-structured applications that are easier to maintain and extend. With the combination of inheritance, access modifiers, static members, and abstract classes, TypeScript's class system allows for robust object-oriented programming practices. Happy coding!