CodeWithMihir

TypeScript Tutorial

TypeScript Static Members Explained

Learn how static properties and static methods work in TypeScript classes, including utility methods, counters, and common mistakes.

Welcome back! I am Mihir, and in this lesson we will learn static members in TypeScript.

Static members belong to the class itself, not to individual instances.


Static Method

class MathHelper {
  static add(a: number, b: number): number {
    return a + b;
  }
}

console.log(MathHelper.add(10, 20));

You call a static method on the class name.

You do not need to create an object.


Static Property

class AppConfig {
  static appName: string = "CodeWithMihir";
}

console.log(AppConfig.appName);

appName belongs to AppConfig, not to an instance.


Static Counter Example

class User {
  static count = 0;

  constructor(public name: string) {
    User.count += 1;
  }
}

const userOne = new User("Mihir");
const userTwo = new User("Alex");

console.log(User.count);

This logs:

2

Static Members Are Not on Instances

Invalid:

const helper = new MathHelper();
helper.add(1, 2);

add is static, so it must be called like this:

MathHelper.add(1, 2);

Static Methods Cannot Use Instance this

class User {
  constructor(public name: string) {}

  static createGuest() {
    return new User("Guest");
  }
}

Static methods can create instances, but they cannot directly access instance properties like this.name.


Common Use Cases

Static members are useful for:

  • utility functions
  • factory methods
  • shared counters
  • constants
  • configuration values

Quick Recap

  • Static members belong to the class itself.
  • Use the class name to access static properties and methods.
  • Static members are not available on instances.
  • Static methods are useful for helpers and factories.
  • Instance data belongs to objects created from the class.

Next up, we start generics with Introduction to Generics →.