Categories
TypeScript Answers

How to use get and set in TypeScript?

Spread the love

Sometimes, we want to use get and set in TypeScript.

In this article, we’ll look at how to use get and set in TypeScript.

How to use get and set in TypeScript?

To use get and set in TypeScript, we can put it in a class.

For instance, we write:

class Foo {
  private _bar: boolean = false;
  get bar(): boolean {
    return this._bar;
  }
  set bar(value: boolean) {
    this._bar = value;
  }
}

to add a bar instance variable with get and set.

In get bar, we return the value of this._bar.

And we add set bar to set the value of this._bar to `value.

get is used for creating getter instance variables.

And set is used creatring setter instance variables.

We can then set bar with

const myFoo = new foo();
myFoo.bar = false;

and get bar with myFoo.bar.

Conclusion

To use get and set in TypeScript, we can put it in a class.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *