Generic classes
Concept and syntax
A generic class parameterizes its instance contract. A constructor can infer the type parameter from the supplied value, while an explicit argument sets it. Static members cannot refer to the class type parameter because all instances share the same runtime constructor.
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.
class Box<T>{constructor(private value:T){}get():T{return this.value;}set(value:T){this.value=value;}}const b=new Box<number>(3);b.set(7);const t=new Box("tea");console.log(b.get(),t.get());Expected output:
7 teaCommon mistake
Intentionally invalid; compile separately and do not execute.
class Box<T>{constructor(private value:T){}set(value:T){this.value=value;}}new Box<number>(3).set("7");Expected diagnostic: TS2345. The instance uses T=number. Set a numeric value.
Practice and recap
Create two Box instances with different element types.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generic classes — 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)?
class Box<T>{constructor(private value:T){}get():T{return this.value;}set(value:T){this.value=value;}}const b=new Box<number>(3);b.set(7);const t=new Box("tea");console.log(b.get(),t.get());Which diagnostic and explanation match the rejected example under the lesson settings?
class Box<T>{constructor(private value:T){}set(value:T){this.value=value;}}new Box<number>(3).set("7");