ConstructorParameters with Abstract Classes
You'll learn how ConstructorParameters<T> handles abstract classes and their constructor signatures, including what it extracts and when you can't directly use those parameters.
Core Idea
When you apply ConstructorParameters to an abstract class, TypeScript extracts the parameter types from that abstract class's constructor just like it does with regular classes. However, there's a crucial difference: you cannot directly instantiate an abstract class, even though you can still analyze its constructor signature.
This becomes useful when creating concrete subclasses or factory functions that need to match the abstract class's constructor shape.
How It Works
Abstract classes can have constructors with parameters. Even though you cannot call new AbstractClass() directly, ConstructorParameters<typeof AbstractClass> successfully extracts those parameter types:
abstract class Vehicle {
constructor(public wheels: number, public color: string) {}
abstract move(): void;
}
type VehicleParams = ConstructorParameters<typeof Vehicle>;
// Result: [wheels: number, color: string]
This extracted type can help you ensure that concrete classes or factory functions pass the correct arguments up to the abstract base constructor.
Practical Pattern: Factory Functions
When building factories that create instances of concrete subclasses, you can use ConstructorParameters to type-check the base parameters:
abstract class Animal {
constructor(public name: string, public age: number) {}
abstract speak(): string;
}
class Dog extends Animal {
speak() { return "Woof!"; }
}
type AnimalParams = ConstructorParameters<typeof Animal>;
function createDog(...params: AnimalParams): Dog {
return new Dog(...params); // Correctly typed!
}
Key Takeaway: ConstructorParameters works with abstract classes to extract constructor parameter types, enabling type-safe factories and ensuring subclasses receive properly-typed base constructor arguments, even though abstract classes themselves cannot be instantiated.