Start learning free

LESSON 401 OF 414 · OBJECT-ORIENTED PROGRAMMING

Static Members in TypeScript in TypeScript

Practice

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

    Static Members in TypeScript

    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free