How to use getters or setters in interface definition with TypeScript?

Sometimes, we want to use getters or setters in interface definition with TypeScript.

In this article, we’ll look at how to use getters or setters in interface definition with TypeScript.

How to use getters or setters in interface definition with TypeScript?

To use getters or setters in interface definition with TypeScript, we can implement an interface property with a class with getters and setters.

For instance, we write

interface IExample {
  name: string;
}

class Example implements IExample {
  private _name: string = "jane";

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

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

const example = new Example();

to create the Example class that implements the IExample interface.

In it, we have the name getter and setter which gets and sets the value of the _name instance variable respectively.

We defined the getter with get and the setter with set.

Conclusion

To use getters or setters in interface definition with TypeScript, we can implement an interface property with a class with getters and setters.