0
0
Typescriptprogramming~5 mins

Static members with types in Typescript

Choose your learning style9 modes available
Introduction

Static members belong to the class itself, not to any object. They help share data or functions across all objects without repeating them.

When you want to keep a count of how many objects of a class are created.
When you need a utility function that doesn't depend on object data.
When you want to store a value common to all objects, like a configuration setting.
When you want to group related constants inside a class.
When you want to access a method or property without creating an object.
Syntax
Typescript
class ClassName {
  static staticMemberName: Type = initialValue;
  static staticMethodName(): ReturnType {
    // method code
  }
}

Use the static keyword before the member name.

Static members are accessed using the class name, not an object.

Examples
This defines a static number property count initialized to 0.
Typescript
class Counter {
  static count: number = 0;
}
This defines a static method greet that returns a greeting string.
Typescript
class Helper {
  static greet(): string {
    return "Hello!";
  }
}
Static members are accessed directly on the class, not on instances.
Typescript
console.log(Counter.count); // Access static property
console.log(Helper.greet()); // Call static method
Sample Program

This program shows a class with static properties and a static method. It counts how many accounts are created and shows the bank name and total accounts.

Typescript
class BankAccount {
  static bankName: string = "Safe Bank";
  static totalAccounts: number = 0;

  accountNumber: number;
  balance: number;

  constructor(accountNumber: number, balance: number) {
    this.accountNumber = accountNumber;
    this.balance = balance;
    BankAccount.totalAccounts++;
  }

  static getBankInfo(): string {
    return `Bank: ${BankAccount.bankName}, Total Accounts: ${BankAccount.totalAccounts}`;
  }
}

const acc1 = new BankAccount(101, 500);
const acc2 = new BankAccount(102, 1000);

console.log(BankAccount.getBankInfo());
OutputSuccess
Important Notes

Static members cannot access instance members directly because they belong to the class, not objects.

You can use static members to store data or functions that should be shared by all instances.

Summary

Static members belong to the class, not to individual objects.

Use static keyword to declare static properties or methods with types.

Access static members using the class name, not an instance.