Static properties and methods in TypeScript
21 A static counter
easyWrite a counter class with a static count starting at zero, a static method that adds one, and a static method that returns the current value. Call both and check the result.
Stuck? Three hints, smallest first
- 1.
staticmembers belong to the class, so you call them asCounter.increment(). - 2. Instances cannot see statics:
new Counter().countisundefined. - 3. Making the count private and exposing it through a static getter stops outside code setting it directly.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
class Counter {
// Private, so nothing outside can set it to 900 directly.
private static count = 0;
static increment(): void {
Counter.count += 1;
}
static getCount(): number {
return Counter.count;
}
static reset(): void {
Counter.count = 0;
}
}
Counter.increment();
Counter.increment();
Counter.increment();
console.log('after three increments:', Counter.getCount());
Counter.reset();
console.log('after reset:', Counter.getCount());
Counter.increment();
// Counter.count = 900; // error: Property 'count' is private
test('three increments', (() => { Counter.reset(); Counter.increment(); Counter.increment(); Counter.increment(); return Counter.getCount(); })(), 3);
test('reset works', (() => { Counter.reset(); return Counter.getCount(); })(), 0);
test('increment after reset', (() => { Counter.reset(); Counter.increment(); return Counter.getCount(); })(), 1);
Output
Making the field private static is the detail worth copying. A plain static count = 0 can be set to anything by any caller, which makes the counter a suggestion. Private plus a getter means the only way the number changes is through increment().