Typescript set & get methods| Encapsulation Examples

In this Blog Post, learn the getter and setetter Accessor methods or Encapsulation in typescript.

Getters and Setters are used to have control of the member variables of a class in typescript.

It allows for encapsulation of the object state and provides a way to change or get the state.

with this, 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 contains two things.

  • member variables or properties to store data
  • Functions/method code that manipulates the data or variables or properties.

Data is protected from the outside world thus it can’t be accessed directly, but it can be accessed via methods/functions code. These methods or functions are called setter and getter

This enables the developer to access the data at the specific entry point and easy to debug the code when anything error occurs.

Typescript provides encapsulation using set and gets accessor methods

  • Define the member variables as private keyword
  • Declare public set and get methods for updating and reading member variable

As typescript is static type checking, there is no code generated while compiled 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

Here Employee object contains a private name property., Private modifier properties allow access inside the class only and will not be accessible outside. To make it simple, provided getter/setter methods for the name and added a public access modifier to access/manipulate outside class.

Typescript declares a private variable by prefixing underscore(_).

get name() allows to read the name value of an Employee object.

set name() allows to modification of a name property of an Employee object.

This is a set and gets accessor method example

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 and enables data to be accessible via getter and setter accessor methods.
  • It is very easy to debug when checking property variable data for correctness

Typescript Interface set and get Accessor methods

Typescript does not support setter/getter methods in interfaces directly. We have to use a different syntax.

The interface has to provide only member variables and does not provide an implementation for these properties.

The implementation class uses 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

Following are naming conventions for the setter and getter of a variable in a class

  • Setter & getter Convention For example, if the Student contains the marks property, Then the setter convention is set marks(value). It assigns the value to a private variable.
class Student {
  private _marks: number;

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

if a class contains marks property, Then the getter convention is get marks() It updates the value to a private variable.

class Student {
  private _marks: number;

  get marks(): number {
    return this._marks;
  }
}
  • CamelCase for names

if the class contains private variables of 2 or more words, use camelCase.

if the name is fullName, the first character of the first word is lower case, and the first character of the second word is upper case.

It applies to private variables and setter and getter names also.

class Student {
  private _fullName: string;

  get fullName(): string {
    return this._fullName;
  }
  set fullName(value: string) {
    this._fullName = value;
  }
}
  • setter and getter should not have complex logic. It should have read and updated the values of private property of a class
  • The suffix of get and set should have the same name.
  • Don’t prefix set or get to variable names
// not recommended to use prefix get
getName(): string {
}

// recommended
setName(value: string): void {
}
  • get and set are reserved keywords in the typescript, not used for variable declaration.
  • Used for data validation and provide a controlled access