Course contentsShow
← TypeScript
Lesson 1061 of 1,79624. Classes in TypeScriptFree lesson

Static Members in Inheritance

Learn how static members are inherited by subclasses and how to override or shadow them.

Static Members in Inheritance

You'll learn: How static members behave when classes inherit from each other, and what happens when a subclass defines its own static members with the same name as the parent's.

The Core Idea

In TypeScript, static members belong to the class itself, not to instances. When you create a class hierarchy with extends, static members are inherited by the subclass—but there's a twist: the subclass gets its own "copy" of the static member that shadows the parent's.

Think of it like family heirlooms. When a family (subclass) inherits from another (parent class), they receive their own version of the heirloom. They can keep it as-is, or replace it with their own customized version. Both families still have their original heirlooms intact—they don't share the same physical object.

Accessing Inherited Static Members

When a subclass extends a base class, it inherits all static members. You can access them through the subclass name:

class Database {
  static connectionLimit = 10;
  
  static getVersion(): string {
    return "1.0.0";
  }
}

class MySQLDatabase extends Database {
  // Inherits connectionLimit and getVersion
}

console.log(MySQLDatabase.connectionLimit);  // 10
console.log(MySQLDatabase.getVersion());     // "1.0.0"

Shadowing Static Members

A subclass can define its own static member with the same name, which shadows (or overrides) the parent's version:

class Database {
  static connectionLimit = 10;
}

class MySQLDatabase extends Database {
  static connectionLimit = 50;  // Shadows parent's value
}

console.log(Database.connectionLimit);       // 10
console.log(MySQLDatabase.connectionLimit);  // 50

Both classes maintain their own values—changing one doesn't affect the other.

Static Methods and this

In static methods, this refers to the class itself. When inherited, this correctly refers to the subclass:

class Database {
  static connectionLimit = 10;
  
  static describe(): string {
    return `This database allows ${this.connectionLimit} connections`;
  }
}

class PostgresDatabase extends Database {
  static connectionLimit = 100;
}

console.log(Database.describe());         // "...10 connections"
console.log(PostgresDatabase.describe()); // "...100 connections"

Key Takeaway: Static members are inherited by subclasses and can be accessed through the subclass name. Subclasses can shadow static members by declaring their own with the same name, creating independent values for each class in the hierarchy.