Objects and Classes
TS Classes
Creating TypeScript Classes
TypeScript classes add typed properties and methods with access modifiers.
Introduction to TypeScript Classes
TypeScript classes are a blueprint for creating objects with typed properties, methods, and access control. They enable structured and maintainable code by enforcing typing and providing encapsulation via access modifiers. In this guide, we explore the key features of TypeScript classes, enhancing your ability to write robust applications.
Defining a Basic Class
At the core of TypeScript classes is the ability to define a template for creating objects. Here's how you can define a basic class:
In this example, the Person
class has two properties: name
and age
. The constructor initializes these properties, and the greet
method outputs a greeting message.
Type Annotations in Classes
TypeScript enhances JavaScript classes with type annotations, ensuring that each property and method parameter has a defined type. This helps catch errors during development:
The Car
class uses type annotations to define the make
, model
, and year
properties as strings and a number, respectively. This type safety is a core advantage of using TypeScript.
Access Modifiers: public, private, and protected
Access modifiers in TypeScript control the visibility of class members. By default, all properties and methods are public
. You can use private
and protected
to restrict access:
In the BankAccount
class, the balance
property is marked as private
, meaning it can only be accessed within the class. The deposit
and getBalance
methods allow controlled interaction with the balance.
Implementing Interfaces with Classes
TypeScript classes can implement interfaces to ensure that a class adheres to a specific contract. This promotes consistency and reliability:
Both Circle
and Square
classes implement the Drawable
interface, ensuring they both have a draw
method. This pattern benefits large applications where consistency across multiple class implementations is crucial.
Conclusion and Next Steps
TypeScript classes provide a powerful mechanism for building scalable and maintainable applications. Understanding how to define and use classes with type annotations and access modifiers is essential for leveraging TypeScript's full potential. In the next post, we'll explore Inheritance in TypeScript, a key concept for creating complex class hierarchies.
Objects and Classes
- Previous
- Interfaces
- Next
- Inheritance