Start learning free

LESSON 29 OF 70 · OBJECT-ORIENTED PROGRAMMING

Static Members in TypeScript: Counting Objects with static

Practice Read the full explanation

TL;DR:

A static property is declared with the static keyword and a type. It belongs to the class itself, so there is one copy shared by every Dog, and you reach it through the class name: Dog.count, not this.count. The same keyword also makes static methods.

You start with:

class Dog {
    name: string;

    constructor(name: string) {
        this.name = name;
    }
}

Your task: count how many Dog objects have been created, with one counter shared by all of them.

  • Add the static property static count: number = 0; inside Dog.
  • In the constructor, after the name assignment, add Dog.count++;. A static member is not available as this.count.
  • The counter starts at 0 before any dog exists, and goes up by exactly 1 for every dog created, whatever its name.
  • The program that is already in the editor creates Rex and Buddy and prints the counter; then it creates Max, prints the counter and Max's name, creates Luna, and prints the counter once more. Do not change those lines.

Expected output:

2
3
Max
4

Read the counter with Dog.count.

class Dog {
    static count: number = 0;
    name: string;

    constructor(name: string) {
        this.name = name;
        Dog.count++;
    }
}

let rex: Dog = new Dog("Rex");
let buddy: Dog = new Dog("Buddy");
console.log(Dog.count);
let third: Dog = new Dog("Max");
console.log(Dog.count);
console.log(third.name);
new Dog("Luna");
console.log(Dog.count);

STEP 1 OF 2
    Ctrl + Enter to check

    TYPESCRIPT · OBJECT-ORIENTED PROGRAMMING

    Static Members in TypeScript, explained

    Problem overview

    The lesson starts with a Dog class that has a name and a constructor. The task is to count how many Dog objects have been created, using one counter shared by all of them. The counter must be 0 before any dog exists and go up by exactly 1 for every dog created, whatever its name.

    The program already in the editor creates Rex and Buddy and prints the counter, creates Max, prints the counter and Max's name, then creates Luna and prints the counter again. You don't change those lines. The expected output is:

    2
    3
    Max
    4
    

    What a static member is

    Normal properties such as name belong to each object: every Dog has its own copy. A static member belongs to the class itself. There is exactly one copy of it, no matter how many objects exist, and it is reached through the class name: Dog.count.

    That is what a shared counter needs. If count were an ordinary property, every dog would carry its own counter, and each would only ever know about itself. A static property gives all the dogs, and the code that creates them, one place to read and update.

    The keyword static also works for methods. A static method is called on the class (Dog.something()) and has no particular dog to work on.

    Because the static field lives on the class, it is created when the class is defined and exists for the whole run of the program. It does not depend on any dog: Dog.count can be read before the first new Dog(...), and it then gives 0. Every object creation after that runs the constructor, and the constructor is the one place where the counter changes.

    Step by step

    1. Declare the static field. At the top of the class, write static count: number = 0;. The static keyword attaches it to Dog, the type is number, and the initial value 0 is set once, when the class is defined, before any dog exists.
    2. Count each new dog. At the end of the constructor, after the name assignment, write Dog.count++;. The constructor runs once for every new Dog(...), so the counter goes up by one per dog.

    The lines below the class stay as they are. After Rex and Buddy the counter is 2. After Max it is 3, and the program prints Max's name. Luna is created without being stored in a variable, and the constructor still counts it, so the last line prints 4.

    The solution in TypeScript

    class Dog {
        static count: number = 0;
        name: string;
    
        constructor(name: string) {
            this.name = name;
            Dog.count++;
        }
    }
    
    let rex: Dog = new Dog("Rex");
    let buddy: Dog = new Dog("Buddy");
    console.log(Dog.count);
    let third: Dog = new Dog("Max");
    console.log(Dog.count);
    console.log(third.name);
    new Dog("Luna");
    console.log(Dog.count);
    

    Language details

    The common mistake is to write this.count++ inside the constructor, as you would for name. In TypeScript, this is the new dog, and a static member does not live on the dog. Take a small class written this way:

    class Cat {
        static count: number = 0;
        name: string;
        constructor(name: string) {
            this.name = name;
            this.count++;
        }
    }
    

    The compiler reports:

    error TS2576: Property 'count' does not exist on type 'Cat'. Did you mean to access the static member 'Cat.count' instead?
    

    The error doesn't stop the JavaScript from being produced, but the program is wrong. After one new Cat("a"), Cat.count is still 0, and the cat itself has a count of NaN: reading a missing property gives undefined, and undefined + 1 is NaN. The counter that was supposed to be shared never changes.

    Reading through an instance fails in the same way. In the lesson's program, third.count would also be reported as an error, and its value would be undefined because the dog object has no such property. The static field is on the class: use Dog.count.

    Also note that a static field does not appear on the objects. For the first dog in the lesson, Object.keys(rex) is ["name"].

    The opposite choice, a plain instance field count: number = 0 incremented with this.count++, would give every dog its own counter. After creating three cats this way, the last one reports 1, not 3, because each object increments its own field once.

    Edge cases and common mistakes

    • Using this.count instead of Dog.count. The compiler flags it, and the counter never moves, as shown above.
    • Forgetting the initial value. static count: number; without = 0 leaves the counter undefined, and undefined++ gives NaN. The statement says the counter starts at 0, so it needs the initializer.
    • Incrementing outside the constructor. Putting Dog.count++ in the program, next to each new Dog(...), would work only until someone forgets one. In the constructor it is done for every dog, including Luna, which is never stored in a variable.
    • Counting by name. The count depends on how many objects are created, not on their names. Two dogs with the same name still count as two.

    Key takeaways

    • static puts a member on the class, not on each object: one shared copy.
    • Reach a static member through the class name, Dog.count, never through this or an instance.
    • Give the static field a type and an initial value in its declaration.
    • Updating a static counter in the constructor counts every object, however it is created.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free