Const Type Parameters

Inferring the most narrow, literal type automatically (TS 5.0).

TypeScript4 min readConcept 26 of 54

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.

Generic Definition:
// TS 5.0+ Generic Modifier
function route<
const
T>(paths: T) {
return paths;
}

// Caller passes an inline array
const res = route(["/home", "/about"]);
Type Inference Result
string[]

Wide Array • Mutable

readonly ["/home", "/about"]

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.

  1. 1What happens if a user passes `const myArr = [1, 2]; myFunction(myArr);` to a function defined as `function myFunction<const T>(arr: T)`?

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 const to 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.