Typescript Foundations / Class & Object Oriented Typescript

Static Properties and Methods

  • Static members are accessed on the class, not on individual objects (instances).

  • They’re used for utility functions, constants, counters, or anything that’s shared across all instances.


✅ Basic Syntax

class MathHelper {
  static PI: number = 3.14159;

  static square(n: number): number {
    return n * n;
  }
}

// Accessing static members
console.log(MathHelper.PI);           // ✅ 3.14159
console.log(MathHelper.square(5));    // ✅ 25

❌ You cannot access static properties via an object instance.

const helper = new MathHelper();
console.log(helper.PI);            // ❌ Error: Property 'PI' does not exist on type 'MathHelper'

📦 Real-World Use Case: ID Generator

class User {
  private static count = 0;
  public id: number;

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

  static getUserCount(): number {
    return User.count;
  }
}

const u1 = new User("Tisha");
const u2 = new User("Riya");

console.log(User.getUserCount());   // ✅ 2

🔒 Access Modifiers with static

You can use public, private, or protected with static properties too.

class AppConfig {
  private static API_KEY = "xyz123";

  static getKey(): string {
    return this.API_KEY; // ✅ OK: private, but within class
  }
}

🧠 Static vs Instance

Feature

Static

Instance

Belongs to

Class itself

Each object created

Accessed via

ClassName.property

instance.property

Shared across all

✅ Yes

❌ No


🧪 Example with Static + Instance


✅ Summary Table

Keyword

Use For

Accessed With

static

Class-level props/methods

ClassName.member

this inside static

Refers to the class itself

Not the instance