Const type parameters
Concept and syntax
A const type parameter requests more literal-preserving inference for suitable inline arguments. For an inline array, a readonly array constraint allows tuple-like inference. It does not freeze runtime values or recover literals from an already widened variable. Choose constraints that accommodate the inferred readonly shape.
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 keep<const T extends readonly string[]>(x:T):T{return x;}const pair=keep(["a","b"]);const first:"a"=pair[0];console.log(first,pair.length);Expected output:
a 2The explicit first annotation checks that the first element retained the literal "a", not just string. The array constraint is readonly, so the inferred tuple permits reading but rejects push.
Common mistake
Intentionally invalid; compile separately and do not execute.
function keep<const T extends readonly string[]>(x:T):T{return x;}const pair=keep(["a","b"]);pair.push("c");Expected diagnostic: TS2339. The inline argument is inferred as a readonly tuple. Use a mutable copy for mutation.
Practice and recap
Pass a previously declared string[] and compare inference with the inline array.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Const type parameters — 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 keep<const T extends readonly string[]>(x:T):T{return x;}const pair=keep(["a","b"]);const first:"a"=pair[0];console.log(first,pair.length);Which diagnostic and explanation match the rejected example under the lesson settings?
function keep<const T extends readonly string[]>(x:T):T{return x;}const pair=keep(["a","b"]);pair.push("c");