Encapsulation in TypeScript: Safeguarding Data with Private Members and Accessors
Introduction And Learning Goals
Hello! Today's journey ventures into the cornerstone of TypeScript's object-oriented fundamentals: Encapsulation. This concept establishes a protective barrier around an object's data, thereby preventing it from being accessed by the external code ecosystem. Let's dive in.
Why Encapsulation?
Encapsulation serves three main purposes: it maintains integrity, controls data modification, and provides data abstraction — interfaces that are accessible to users. Think of using a cell phone; you interact with an interface without interfering with its circuits. Following this logic, encapsulation safeguards the internal implementation while exposing safe interfaces.
Private Data In TypeScript
Now, let's discuss Private Data: In TypeScript, we can specify private data using the keyword private. These data fields cannot be accessed outside the class. We will illustrate this with a Car class, introducing a private attribute called _speed:
This class has a private member, _speed, which cannot be accessed directly outside the class. The underscore _ before speed is a naming convention that indicates it is a private attribute.
Using Getters And Setters
Getters and Setters are tools used to control access to private data. In our Car class, a getter function retrieves the _speed attribute, while a setter function modifies it as follows:
These methods allow us to retrieve or change the car's speed in a safe manner.
Bringing It All Together
