Categories
TypeScript Answers

How to add a private setter with TypeScript?

Spread the love

Sometimes, we want to add a private setter with TypeScript.

In this article, we’ll look at how to add a private setter with TypeScript.

How to add a private setter with TypeScript?

To add a private setter with TypeScript, we can use the private keyword.

For instance, we write

class Test {
  _prop: string;
  public get prop(): string {
    return this._prop;
  }

  private get internalProp(): string {
    return this.prop;
  }

  private set internalProp(value: string) {
    this._prop = value;
  }

  private addToProp(valueToAdd: string): void {
    this.internalProp += valueToAdd;
  }
}

to create the internalProp setter that sets the this._prop value to value.

Then we can use the setter as we do in the addToProp by assigning a value to this.internalProp.

Conclusion

To add a private setter with TypeScript, we can use the private keyword.

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 *