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:

class Car {
    private _speed: number; // private speed attribute

    constructor() {
        this._speed = 0; // Initialize speed with 0
    }
}

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:

class Car {
    private _speed: number; // Private speed attribute

    constructor() {
        this._speed = 0; // Initialize speed with 0
    }

    get speed(): number { // Get current speed
        return this._speed;
    }

    set speed(value: number) { // Update speed
        // Speed should stay in the range 0 to 150
        if (value < 0) {
            this._speed = 0;
        } else if (value > 150) {
            this._speed = 150;
        } else {
            this._speed = value;
        }
    }
}

These methods allow us to retrieve or change the car's speed in a safe manner.

Bringing It All Together
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