Typescript set & get methods| Encapsulation Examples

In this blog post, you’ll learn about getter and setter accessor methods, also known as encapsulation, in TypeScript.

Getters and setters are utilized to control the member variables of a class in TypeScript. They facilitate encapsulation of the object state and offer a means to modify or retrieve the state.

With these, you can achieve encapsulation in TypeScript.

What is Encapsulation in Typescript?

It is one of the concepts of Object-Oriented Programming. Other concepts are

Each class or object typically comprises two components:

  • Member variables or properties to store data.
  • Functions/methods that manipulate the data or variables.

Data is protected from the outside world, preventing direct access. However, it can be accessed via methods or functions. These methods or functions are commonly referred to as setter and getter methods.

This approach enables developers to access the data at specific entry points, making it easier to debug code when errors occur.

TypeScript provides encapsulation using setter and getter accessor methods:

  • Define member variables as private using the private keyword.
  • Declare public set and get methods for updating and retrieving member variables.

Since TypeScript offers static type checking, no code is generated when compiling to JavaScript.

How to enable setters and getters using Compiler target options?

The typescript compiler does not support setters and getters accessors by default.

To enable this, We need to modify typescript compiler options with target ES5. Otherwise,“error TS1056: Accessors are only available when targeting ECMAScript 5 and higher.” is thrown.

tsc command configuration You have provided compiler options for the tsc command tool.

tsc --target ES5

Update tsconfig.json target options In the Angular application, To support set and get accessor syntax, We have to modify tsconfig.json with compilerOptions - target - es5

{
    "compilerOptions": {
        "target": "es5"
            ........
  }
}

TypeScript Encapsulation Class Example

In this example, an Employee object contains a private name property. Private modifier properties allow access only inside the class and are not accessible from outside.

To simplify access, getter and setter methods are provided for the name, with a public access modifier to allow manipulation from outside the class.

TypeScript declares private variables by prefixing them with an underscore (_).

The get name() method allows reading the name value of an Employee object, while set name() allows modification of the name property.

This is an example of setter and getter accessor methods:

export class Employee {
  private _name: string;

  constructor() {}

  // Getter for the name property
  public get name(): string {
    return this._name;
  }

  // Setter for the name property
  public set name(val: string) {
    this._name = val;
  }
}

export default Employee;

Advantages

  • Data is hidden, enabling access via getter and setter accessor methods.
  • Debugging becomes simpler when verifying the correctness of property variable data

TypeScript Interface with Setter and Getter Accessor Methods

TypeScript doesn’t directly support setter/getter methods in interfaces. Instead, we need to use a different syntax.

The interface should only declare member variables without providing an implementation for these properties.

The implementing class then utilizes setters and getters to access the member variable.

interface MyInterface {
  name: string;
}

class MyClass implements MyInterface {
  private name: string = "Kiran";

  public get name() {
    return this._name;
  }

  public set name(value: string) {
    this._name = value;
  }
}

var myClass = new MyClass();
console.log(myClass.name);

TypeScript Setter and Getter Naming Convention

Below are the naming conventions for setters and getters of a variable in a class:

  • Setter & Getter Convention: For instance, if the Student class contains the marks property, the setter convention is set marks(value), which assigns the value to a private variable.

    class Student {
      private _marks: number;
    
      set marks(value: number) {
        this._marks = value;
      }
    }
    

    Similarly, if a class contains a marks property, the getter convention is get marks(), which retrieves the value from a private variable.

    class Student {
      private _marks: number;
    
      get marks(): number {
        return this._marks;
      }
    }
    
  • CamelCase for Names If a class contains private variables with two or more words, use camelCase. For example, if the name is fullName, the first character of the first word is lowercase, and the first character of the second word is uppercase. This convention applies to private variables and their setter and getter names as well.

    class Student {
      private _fullName: string;
    
      get fullName(): string {
        return this._fullName;
      }
      set fullName(value: string) {
        this._fullName = value;
      }
    }
    
  • Setter and Getter Logic:

    • Setter and getter methods should not have complex logic. They should simply read and update the values of private properties of a class.

    • The suffix of get and set methods should have the same name.

    • It’s not recommended to prefix get to variable names. Instead, use a method name like getName(). For setters, it’s recommended to use a method name like setName(value: string): void.

    // not recommended to use prefix get
    getName(): string {
    }
    
    // recommended
    setName(value: string): void {
    }
    
    • get and set are reserved keywords in TypeScript and should not be used for variable declarations. They are used for data validation and providing controlled access.