Generic defaults
Concept and syntax
A generic parameter can declare a default T = string. When no type argument is supplied and inference does not choose a candidate, the default applies. Explicit arguments still specialize the type. Defaults must satisfy any declared constraint and required parameters cannot follow optional ones.
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.
type Box<T=string>={value:T};const a:Box={value:"tea"};const b:Box<number>={value:7};console.log(a.value,b.value);Expected output:
tea 7Common mistake
Intentionally invalid; compile separately and do not execute.
Expected diagnostic: TS2322. Omitting the type argument uses string here. Specify Box<number> for a numeric value.
Practice and recap
Add a constrained default that satisfies a length property.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generic defaults — 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)?
type Box<T=string>={value:T};const a:Box={value:"tea"};const b:Box<number>={value:7};console.log(a.value,b.value);Which diagnostic and explanation match the rejected example under the lesson settings?
type Box<T=string>={value:T};const a:Box={value:7};