Generic interfaces and aliases
Concept and syntax
A generic interface or alias parameterizes a reusable shape. Box<number> and Box<string> share the same declaration but specialize its content type. Generic parameters constrain the declared fields; they do not create new runtime classes. Provide explicit type arguments when the declaration requires them.
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.
interface Box<T>{value:T;}type Pair<T>={left:T;right:T};const b:Box<number>={value:7};const p:Pair<string>={left:"a",right:"b"};console.log(b.value,p.left+p.right);Expected output:
7 abCommon mistake
Intentionally invalid; compile separately and do not execute.
interface Box<T>{value:T;}const b:Box<number>={value:"7"};Expected diagnostic: TS2322. The specialized Box requires number for value. Use the right payload or type argument.
Practice and recap
Define Box<boolean> and Pair<number> and initialize both.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generic interfaces and aliases — 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)?
interface Box<T>{value:T;}type Pair<T>={left:T;right:T};const b:Box<number>={value:7};const p:Pair<string>={left:"a",right:"b"};console.log(b.value,p.left+p.right);Which diagnostic and explanation match the rejected example under the lesson settings?
interface Box<T>{value:T;}const b:Box<number>={value:"7"};