TypeScript - Accessors

Hello there, aspiring programmers! Today, we're going to dive into the fascinating world of TypeScript accessors. Don't worry if you're new to programming – I'll guide you through this topic step by step, just like I've done for countless students over my years of teaching. So, grab a cup of your favorite beverage, and let's get started!

TypeScript - Accessors

What are Accessors?

Before we jump into the specifics of TypeScript accessors, let's understand what accessors are in general. Imagine you have a treasure chest (that's our object), and you want to control how people interact with the treasures inside (the object's properties). Accessors are like the magical keys that allow you to get or set these treasures in a controlled manner.

In TypeScript, we have two types of accessors:

  1. Getters: These help us retrieve the value of a property.
  2. Setters: These allow us to set the value of a property.

Now, let's explore each of these in detail.

Getters in TypeScript

What is a Getter?

A getter is a special kind of method that allows you to access a property of an object. It's like having a personal assistant who fetches information for you.

How to Define a Getter

Let's look at a simple example:

class Person {
    private _name: string;

    constructor(name: string) {
        this._name = name;
    }

    get name(): string {
        console.log("Getting the name");
        return this._name;
    }
}

let person = new Person("Alice");
console.log(person.name); // Output: Getting the name \n Alice

In this example:

  • We have a Person class with a private property _name.
  • We define a getter called name using the get keyword.
  • When we access person.name, it calls our getter method.

Why Use Getters?

  1. Computed Properties: Getters can return computed values.
class Circle {
    private _radius: number;

    constructor(radius: number) {
        this._radius = radius;
    }

    get area(): number {
        return Math.PI * this._radius ** 2;
    }
}

let circle = new Circle(5);
console.log(circle.area); // Output: 78.53981633974483
  1. Lazy Loading: Getters can help with performance by loading data only when needed.
class DataFetcher {
    private _data: string | null = null;

    get data(): string {
        if (this._data === null) {
            console.log("Fetching data...");
            this._data = "Some expensive data";
        }
        return this._data;
    }
}

let fetcher = new DataFetcher();
console.log(fetcher.data); // Output: Fetching data... \n Some expensive data
console.log(fetcher.data); // Output: Some expensive data (no fetching this time)

Setters in TypeScript

What is a Setter?

A setter is like the counterpart to a getter. It's a method that sets the value of a property, often with some additional logic.

How to Define a Setter

Here's a basic example:

class Temperature {
    private _celsius: number = 0;

    set celsius(value: number) {
        if (value < -273.15) {
            throw new Error("Temperature below absolute zero is not possible");
        }
        this._celsius = value;
    }

    get celsius(): number {
        return this._celsius;
    }
}

let temp = new Temperature();
temp.celsius = 25; // This calls the setter
console.log(temp.celsius); // Output: 25

// temp.celsius = -300; // This would throw an error

In this example:

  • We have a Temperature class with a private _celsius property.
  • We define a setter for celsius that checks if the value is valid before setting it.

Why Use Setters?

  1. Data Validation: Setters can ensure that only valid values are assigned to properties.

  2. Side Effects: Setters can trigger other actions when a property is changed.

class User {
    private _name: string = "";
    private _lastUpdated: Date = new Date();

    set name(value: string) {
        this._name = value;
        this._lastUpdated = new Date();
    }

    get name(): string {
        return this._name;
    }

    get lastUpdated(): Date {
        return this._lastUpdated;
    }
}

let user = new User();
user.name = "Bob";
console.log(user.name); // Output: Bob
console.log(user.lastUpdated); // Output: Current date and time

Accessor Methods Table

Here's a summary of the accessor methods we've covered:

Accessor Type Keyword Purpose Example
Getter get Retrieve a property value get name(): string { return this._name; }
Setter set Set a property value set name(value: string) { this._name = value; }

Conclusion

Accessors in TypeScript provide a powerful way to control how object properties are accessed and modified. They allow you to add logic, validation, and computed properties to your classes, making your code more robust and maintainable.

Remember, like learning any new skill, mastering accessors takes practice. Don't be discouraged if it doesn't click immediately – keep coding, keep experimenting, and soon you'll be using getters and setters like a pro!

As I always tell my students, programming is like learning a new language. At first, it might seem confusing, but with patience and practice, you'll soon be "speaking" TypeScript fluently. Happy coding, and don't forget to have fun along the way!

Credits: Image by storyset