Generic factories
Concept and syntax
A constructor-based factory accepts a construct signature new (...) => T and returns an instance of T. The generic parameter connects the constructor result to the factory result. A class instance is not the constructor value; pass the class itself. The example uses a fixed numeric constructor argument.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
function make<T>(C:new(n:number)=>T,n:number):T{return new C(n);}class Meter {constructor(public count:number){}}const m=make(Meter,7);console.log(m.count);Expected output:
7Common mistake
Intentionally invalid; compile separately and do not execute.
function make<T>(C:new(n:number)=>T,n:number):T{return new C(n);}class Meter {constructor(public count:number){}}make(new Meter(7),3);Expected diagnostic: TS2345. The instance has no construct signature. Pass Meter rather than new Meter(7).
Practice and recap
Create another class accepting number and use the same factory.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generic factories — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
function make<T>(C:new(n:number)=>T,n:number):T{return new C(n);}class Meter {constructor(public count:number){}}const m=make(Meter,7);console.log(m.count);Which diagnostic and explanation match the rejected example under the lesson settings?
function make<T>(C:new(n:number)=>T,n:number):T{return new C(n);}class Meter {constructor(public count:number){}}make(new Meter(7),3);