What it is and why to use it
A generic class has instance types for different type arguments, but its static side belongs to the single runtime constructor. A static member therefore cannot refer to the class’s instance type parameter as if separate static storage existed for every T. This matters for caches and counters shared by instances.
Common mistakes and limitations
A declaration such as static defaultValue: T is rejected because static members cannot reference a class type parameter. Generic arguments do not create separate JavaScript classes. Static mutable state can also make tests and application lifecycles harder to isolate.
Run this example
Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.
Terminal — compile and run
npx tsc example.ts --strict --target ES2022 --module commonjs
node example.jsSyntax
class Box<T> { static created = 0; constructor(public value: T) {} }Examples
Generic Instances and Static Members
Standalone TypeScript 5.8+ example; expected output is explained below.
class Box<T> {
static created = 0;
constructor(public value: T) { Box.created += 1; }
}
const text = new Box("Guide");
const number = new Box(7);
console.log(text.value + ": " + number.value);
console.log(Box.created);- The first instance infers T as string and the second infers number.
- Both constructors increment the same Box.created property.
- The total is 2, demonstrating shared static state. A per-type cache needs an explicit runtime key rather than relying on erased generic arguments.
- Expected output: Guide: 7 2
Best practices
- A declaration such as static defaultValue: T is rejected because static members cannot reference a class type parameter. Generic arguments do not create separate JavaScript classes. Static mutable state can also make tests and application lifecycles harder to isolate.
- Keep external-input validation separate from compile-time type descriptions.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook