Codectionary / Developer documentation / TypeScript

Literal Inference with const Type Parameters

TypeScript 5.0 introduced const type parameters to request literal-preserving inference for inline arguments. This can capture a readonly tuple without requiring every caller to add as const. It does not retroactively narrow a variable that was already inferred as a broad mutable array.

Syntax

function tuple<const T extends readonly string[]>(values: T): T { return values; }

Examples

Literal Inference with const Type Parameters: working example

Run this standalone example after compiling with TypeScript 5.4+ in strict mode, targeting ES2022. Expected result: The program prints Ada 2; names retains a readonly tuple type with the two literal names.

function tuple<const T extends readonly string[]>(values: T): T {
  return values;
}
const names = tuple(["Ada", "Grace"]);
const first: "Ada" = names[0];
console.log(first, names.length);
  1. Expected result: The program prints Ada 2; names retains a readonly tuple type with the two literal names.
  2. The readonly constraint accommodates the narrow tuple inferred from the inline array.
  3. The helper returns the original array at runtime, so the type parameter itself adds no copying.

Best practices

  • Use readonly constraints when callers need literal tuple inference.
  • Do not describe const type parameters as runtime immutability.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading