Check out our Angular Book Series.

How do I run extra code when I set a value in TypeScript?

Every once in a while something I'll want to run code when a value is set on a class. Maybe I'll want to validate the input, or maybe I'll want to add additional processing. This code should be built into the class instead of the consumer. TypeScript allows us to do this by creating get and set methods.

Simple Property

A simple class will be something like this:


export class TestClass {
numbers: number[];
counter: number;
}

I just borrowed this from another example I'm working on. It includes a numbers property, which is an array of number values, and a counter value, which is a single number.

To use this class, we create an instance of it:


const testClass = new TestClass();

Then we can access the values:


testClass.numbers = [1, 2, 3, 4];
console.log(testClass.counter);

This is standard and simple.

The Problem

Now let's assume that every time the numbers array is accessed we want to increment the counter. How can we do that? Well, we could do it in the consuming code:


testClass.numbers = [1, 2, 3, 4];
testClass.counter += 1;

But, then the class is less self countained, and we have to remember to update the counter every single time that the numbers is accessed. There must be a better solution.

Solution 1

We could add a method to the class:


setNumber(value) : {
this.numbers = value;
testClass.counter ++;
}

Then our calling code would be like this:


testClass.setNumber([1, 2, 3, 4]);

This is nice because it hides our internal implementation a bit, and would work, but from my consumer I don't want them to have to call a method.

Get/Set properties

Let's change the property into a get/set property. First, make numbers a private variable:


private _numbers: number[]

An underscore was added before the numbers to distinguish it from the public property.

Now, create a get method:


get numbers():number[] {
return this._numbers;
}

This is special syntax. Instead of a normal method, the keyword get is before it. All this does is return the value that represents our numbers property.

We'll also need a setter:


set numbers(value:numbers[]):void {
this._numbers - value;
}

That is great, now from within the consuming code, we treat the get / set methods just like we would a regular property and can access them using the object property notation:


testClass.numbers = [1, 2, 3, 4];
console.log(testClass.counter);

The first line sets the value, and calls the setter. The second line retrieves the value and calls the getter. The internal implementation of the class is unknown to the consumer.

Do more in the set

Inside our class there are get set methods. We can treat them just like any other method and put any code we want in there. For the purposes of this sample I'm going to increment the counter:


set numbers(value:numbers[]):void {
this._numbers - value;
this.counter++;
}

Now, we have side affects when we set the numbers value.

Final Thoughts

There is a lot of flexibility that can be had with getters and setters. For example, in one situation, I had to loop over an array returned rom a remote datasource and pick out one specific item. A get method did it for me, without cluttering up my main Angular component with extraneous data processing code.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.