Concept Flow - Generic factory pattern
Call factory with type T
Create instance of T
Return new instance
Use instance in code
The factory receives a type and creates a new instance of that type, then returns it for use.
class Car { drive() { return 'Driving'; } } function factory<T>(c: new () => T): T { return new c(); } const car = factory(Car); console.log(car.drive());
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Call factory with Car | factory<Car>(Car) | Enter factory function |
| 2 | Create new instance | new Car() | Car instance created |
| 3 | Return instance | return new Car() | Car instance returned |
| 4 | Assign to variable | const car = factory(Car) | car holds Car instance |
| 5 | Call method | car.drive() | 'Driving' returned |
| 6 | Output result | console.log(car.drive()) | Prints: Driving |
| Variable | Start | After Step 2 | After Step 4 | Final |
|---|---|---|---|---|
| car | undefined | Car instance created | Car instance assigned | Car instance with drive method |
Generic factory pattern in TypeScript: - Use a generic function with a constructor signature: function factory<T>(c: new () => T): T - Inside, create instance with 'new c()' - Returns a new instance of type T - Allows creating objects without knowing exact class at compile time - Works for classes with no-argument constructors