Const Type Parameters
Inferring the most narrow, literal type automatically (TS 5.0).
The <const T> modifier
Introduced in TypeScript 5.0, you can add the const modifier to a generic type parameter.
This forces TypeScript to infer the most narrow, literal type possible for whatever argument is passed, exactly as if the caller had written as const.
Improving Developer Experience
Before TS 5.0, if you wanted a function to remember the exact values of an array (e.g., ["alice", "bob"] instead of string[]), you had to beg the caller to add as const to their argument.
With <const T>, the burden shifts from the caller to the function author. The caller just passes a normal array, and the function automatically infers a strict, readonly tuple.
Syntax
typescript
// 1. Without const: Infers wide types
function getRoutes<T>(routes: T) { return routes; }
const r1 = getRoutes(["/home", "/about"]);
// r1 is typed as string[]
// 2. With const: Infers exact literal tuples
function getRoutesConst<const T>(routes: T) { return routes; }
const r2 = getRoutesConst(["/home", "/about"]);
// r2 is strictly typed as readonly ["/home", "/about"]
Try it
Toggle the const modifier on the generic parameter to see how TypeScript drastically changes its inference engine from a wide string[] array to a strict, literal tuple.
Wide Array • Mutable
Strict Tuple • Immutable Literal
TypeScript assumes you might push more strings into the array later, so it infers a wide string[].
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Use
<const T>to automatically infer literal types and readonly tuples (TS 5.0+). - It acts exactly as if the caller had appended
as constto their inline argument. - It improves API ergonomics by not forcing users to write
as const. - It only works on arguments defined inline at the call site.
Done with this concept?
Mark it complete to track your progress. No login needed.