Static Members

Class-Level Fields and Methods

Static Members

`static` declares a field or method on the class itself — not on instances. Use them for factories, constants, and helpers.

3 min read Level 1/5 #typescript#classes#static
What you'll learn
  • Author static fields and methods
  • Use a static factory in place of complex constructors
  • Know the difference between `static` and instance scope

static puts a member on the class itself, not on instances. Call it on the class name.

A Static Method

class MathHelpers {
  static clamp(n: number, min: number, max: number): number {
    return Math.min(Math.max(n, min), max);
  }
}

MathHelpers.clamp(15, 0, 10);   // 10

You never need a MathHelpers instance — just call it on the class.

Static Fields

class Config {
  static readonly DEFAULT_PORT = 3000;
  static readonly VERSION = "1.0.0";
}

console.log(Config.DEFAULT_PORT);   // 3000

A namespaced bag of constants.

Static Factory Methods

A common pattern — provide a named alternative to the constructor:

class Color {
  private constructor(
    public r: number,
    public g: number,
    public b: number,
  ) {}

  static fromHex(hex: string): Color {
    const n = parseInt(hex.slice(1), 16);
    return new Color((n >> 16) & 255, (n >> 8) & 255, n & 255);
  }

  static fromRgb(r: number, g: number, b: number): Color {
    return new Color(r, g, b);
  }
}

const red = Color.fromHex("#ff0000");
const grn = Color.fromRgb(0, 255, 0);

A private constructor forces callers through the named factories — each one tells you what the input is supposed to be.

Static vs Instance — Don’t Mix Up

class C {
  static x = 1;
  y = 2;

  static helloStatic() {
    return this.x;     // ✓ — `this` is the class itself
    // return this.y;   // ✗ — no instance here
  }

  helloInstance() {
    return this.y;     // ✓ — instance
    // return this.x;   // ✗ — instance has no `x`
  }
}

C.helloStatic();          // 1
new C().helloInstance();  // 2

Up Next

implements — promising that a class matches an interface.

`implements` →