TypeScript Reference ยท Classes, Enums and Decorators
TypeScript static class members
Reference for TypeScript static members: static fields, methods, accessors and initialization blocks, inheritance of statics, and the this keyword inside them.
Static members belong to the class itself rather than to its instances. You reach them through the class name (Config.defaults), they exist once, and they are the right place for factories, counters, constants and helpers that do not need an instance.
TypeScript allows static on fields, methods, accessors and static { } initialization blocks. Statics are inherited by subclasses through the constructor's prototype chain.
class Ids { static next = 1; static create(): number { return Ids.next++; } }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
class C { static name = value; static method(): T { ... } static get prop(): T { ... } static { statements } }
| Form | Description |
|---|---|
static field |
One shared value stored on the constructor function. |
static method() |
Callable as C.method(); this is the class when called that way. |
static get / set |
Accessors on the class. |
static { } |
Block run once during class evaluation, with access to private members. A class may have several. |
Edge cases:
- A static member cannot refer to the class's type parameters:
class Box<T> { static x: T }is an error (TS2302). - Names such as
name,lengthandprototypeclash with built-in function properties; static fields with these names are rejected. staticcombines withprivate,protected,readonlyand#privatenames.
Usage notes
- Static blocks run top to bottom with the other static initializers, in source order. Use them for work that needs a try/catch or several statements.
- Inside static code,
thisis the class on which the member was called, so a subclass inherits the method and sees its own overridden static fields. - Detaching a static method (
const f = C.method) losesthis, just like instance methods. - Subclass static types must remain compatible with the base: you cannot redeclare
static kindwith an unrelated type. - Mutable statics are shared global state. They make tests order-dependent; consider injecting dependencies instead.
- For a singleton, combine a private constructor with a static accessor, as shown in Constructors.
Related
- Class fields, Constructors, Inheritance, static keyword
- Lessons: Classes, Access modifiers