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

Armed with these concepts, we can construct a Car class that showcases encapsulation:

And, here is how we will use this class (keep in mind that when using get/set methods, we don't use parentheses):

These codes demonstrate private attributes in action, employing getters and setters and encapsulating the inner workings of the Car class.

Lesson Summary And Practice

Great job getting this far. As a result of this lesson, your toolbelt now includes:

  • An understanding of private data
  • Knowledge about the roles of getters and setters

Inscribe these lessons into your programming mind and continue your journey! There are hands-on exercises in store for you — they offer practical experience and help bond your understanding of the concepts learned. Keep following the path to becoming a TypeScript pro — the journey is worth it!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal