TypeScript
Programming
Web Development
JavaScript
Coding

get and set in TypeScript

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In TypeScript, get and set accessors are special kinds of methods that provide more control over how class members (properties) are accessed and modified. The use of getters and setters can lead to cleaner, more robust and maintainable code. Below we discuss their syntax, usage, functionalities, and some important nuances.

Understanding Getters and Setters

Getters are methods used to read or access the value of an object's property. A getter method returns a value. On the other hand, Setters are methods used to set or update the value of an object's property. Below we look into how these are implemented and used in TypeScript classes.

Syntax and Usage

To define a getter in TypeScript, you use the get keyword followed by the function name. This must not accept any parameters and should return a value:

typescript
1class Person {
2    private _age: number;
3
4    get age(): number {
5        return this._age;
6    }
7}

Similarly, to define a setter in TypeScript, you use the set keyword followed by the function name. This function must accept exactly one parameter and does not return a value:

typescript
1class Person {
2    private _age: number;
3    
4    set age(newAge: number) {
5        if (newAge > 0) {
6            this._age = newAge;
7        } else {
8            throw new Error("Invalid age value");
9        }
10    }
11}

Why Use Getters and Setters?

  1. Encapsulation: They allow for better control over how a property is accessed and modified. You can add validation, logging, or additional logic inside your getter or setter.
  2. Maintainability: Makes it easier to change the underlying implementation without affecting those who depend on the class.
  3. Usability: Classes with getters/setters can often be manipulated more intuitively.

Examples in Action

Consider a class Rectangle for illustrating the practical use:

typescript
1class Rectangle {
2    private _width: number = 0;
3    private _height: number = 0;
4
5    get area(): number {
6        return this._width * this._height;
7    }
8
9    set dimensions({ width, height }: { width: number, height: number }) {
10        this._width = width;
11        this._height = height;
12    }
13}
14
15let rect = new Rectangle();
16rect.dimensions = { width: 5, height: 3 };
17console.log(rect.area);  // Outputs: 15

In this example, dimensions setter allows modifying the _width and _height simultaneously, and area getter calculates the area based on the current dimensions.

Tips and Considerations

  • Setters can perform computations or validations before setting a value.
  • Getters can compute a value rather than simply returning a property.
  • TypeScript strongly types getters and setters; the getter type should match the return type, and the setter type should match the parameter type.

Key Points Summary

FeatureDescriptionConsideration
EncapsulationHide implementation details and validate inputsPrevents object states that you might deem as invalid
ComputationCan compute values in gettersEnsure computations are not too heavy as getters can be called frequently
MaintainabilityUpdate underlying data without affecting consumersSetters and getters can have different signatures (parameter vs return types)

Advanced Topics: Get and Set with Static Properties

TypeScript also supports static getters and setters. These operate on the class itself rather than instances of the class:

typescript
1class MyClass {
2    private static _counter: number = 0;
3
4    public static get counter(): number {
5        return MyClass._counter;
6    }
7
8    public static set counter(value: number) {
9        MyClass._counter = value;
10    }
11}

In this example, MyClass.counter can be used to directly retrieve or modify the relative static field without creating an instance of MyClass.

Conclusion

Understanding and using getters and setters can greatly improve the design and flexibility of your TypeScript applications by encapsulating internal states and exposing safer, potentially computed properties. They are especially useful when paired with strong type-checking capabilities of TypeScript. Remember to leverage these features to create more organized and manageable codebases.


Course illustration
Course illustration

All Rights Reserved.