const Type Parameters in Classes
What you'll learn: How to use const on class type parameters to preserve exact constructor argument types instead of widening them to broader types.
The Problem Classes Face
When you instantiate a generic class with an object or array literal, TypeScript normally wiens the types to be more general. This is usually helpful for mutability, but sometimes you want the class to remember the exact literal types you passed in — just like const type parameters do for functions.
Using const in Class Type Parameters
The const modifier works on class type parameters exactly like it does in functions. When you write:
class Container<const T> {
constructor(public value: T) {}
}
TypeScript will infer T as narrowly as possible when you create instances.
Before and After Comparison
Without const:
class ConfigHolder<T> {
constructor(public config: T) {}
}
const holder = new ConfigHolder({ mode: "production", port: 8080 });
// config type: { mode: string; port: number }
// Lost the literal "production"!
With const:
class ConfigHolder<const T> {
constructor(public config: T) {}
}
const holder = new ConfigHolder({ mode: "production", port: 8080 });
// config type: { mode: "production"; port: 8080 }
// Exact literals preserved!
Why This Matters
This pattern is valuable when building:
- Configuration containers that need exact literal types
- Builder classes that track exact values passed in
- State machines where literal string states matter
- Type-safe registries that remember exact keys
Think of const type parameters as giving your class "photographic memory" — it remembers exactly what you gave it, not just the general category.
Combining with Constraints
You can still use constraints with const type parameters:
class EventBus<const T extends Record<string, unknown>> {
constructor(public events: T) {}
}
const bus = new EventBus({ login: "user-login", logout: "user-logout" });
// events type: { login: "user-login"; logout: "user-logout" }
The constraint ensures structure while const preserves literals.
Key Takeaway: Using const on class type parameters captures constructor argument types as narrowly as possible, preserving literal types and exact shapes instead of widening to broader, mutable types.